How to determine a user's IP address in node

后端 未结 19 1171
天命终不由人
天命终不由人 2020-11-22 12:46

How can I determine the IP address of a given request from within a controller? For example (in express):

app.post(\'/get/ip/address\', function (req, res) {         


        
19条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 13:12

    I have tried all of them didn't work though,

    console.log(clientIp);
    console.log(req.ip);
    
    console.log(req.headers['x-forwarded-for']);
    console.log(req.connection.remoteAddress);
    console.log(req.socket.remoteAddress);
    console.log(req.connection.socket.remoteAddress.split(",")[0]);
    

    When running an Express app behind a proxy for me Nginx, you have to set the application variable trust proxy to true. Express offers a few other trust proxy values which you can review in their documentation, but below steps worked for me.

    1. app.set('trust proxy', true) in your Express app.

    app.set('trust proxy', true);

    1. Add proxy_set_header X-Forwarded-For $remote_addr in the Nginx configuration for your server block.
      location /  {
                    proxy_pass    http://localhost:3001;
                    proxy_http_version 1.1;
                    proxy_set_header Upgrade $http_upgrade;
                    proxy_set_header Connection 'upgrade';
                    proxy_set_header Host $host;
                    proxy_set_header X-Forwarded-For $remote_addr;  # this line
                    proxy_cache_bypass $http_upgrade; 
            }
    
    1. You can now read off the client’s IP address from the req.header('x-forwarded-for') or req.connection.remoteAddress; Full code for ipfilter
    module.exports =  function(req, res, next) {
        let enable = true; // true/false
        let blacklist = ['x.x.x.x'];
        let whitelist = ['x.x.x.x'];
        let clientIp = req.header('x-forwarded-for') || req.connection.remoteAddress;
        if (!clientIp) {
            return res.json('Error');
        }
        if (enable
            && paths.some((path) => (path === req.originalUrl))) {
    
            let blacklist = blacklist || [];
            if (blacklist.some((ip) => clientIp.match(ip) !== null)) {
                return res.json({ status: 401, error: 'Your IP is black-listed !'});
            }
            let whitelist = whitelist || [];
            if (whitelist.length === 0 || whitelist.some((ip) => clientIp.match(ip) !== null)) {
                next();
                return;
            } else {
                return res.json({ status: 401, error: 'Your IP is not listed !'});
            }
        }
        next();
    };
    

提交回复
热议问题