我不完全明白我应该如何获得一个远程用户IP地址。

假设我有一个简单的请求路由,如:

app.get(/, function (req, res){
   var forwardedIpsStr = req.header('x-forwarded-for');
   var IP = '';

   if (forwardedIpsStr) {
      IP = forwardedIps = forwardedIpsStr.split(',')[0];  
   }
});

上面的方法是否正确,以获得真实的用户IP地址或有更好的方法? 那么代理呢?


当前回答

添加app.set('信任代理',true) 使用要求。IP或req。Ips和往常一样

其他回答

根据快递背后的代理,要求。如果正确配置了信任代理,则IP已考虑反向代理。因此,它比req.connection.remoteAddress要好,因为req.connection.remoteAddress是从网络层获取的,不需要代理。

将所有的witk @kakopappa解决方案加上morgan客户端ip地址的日志记录:

morgan.token('client_ip', function getId(req) {
    return req.client_ip
});
const LOG_OUT = ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" :client_ip'
self.app.use(morgan(LOG_OUT, {
    skip: function(req, res) { // custom logging: filter status codes
        return res.statusCode < self._options.logging.statusCode;
    }
}));

// could-flare, nginx and x-real-ip support
var getIpInfoMiddleware = function(req, res, next) {
    var client_ip;
    if (req.headers['cf-connecting-ip'] && req.headers['cf-connecting-ip'].split(', ').length) {
        var first = req.headers['cf-connecting-ip'].split(', ');
        client_ip = first[0];
    } else {
        client_ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
    }
    req.client_ip = client_ip;
    next();
};
self.app.use(getIpInfoMiddleware);

var ip = req.connection.remoteAddress;

IP = IP .split(':')[3];

我为此写了一个包。您可以将其用作表示中间件。我的软件包发布在这里:https://www.npmjs.com/package/express-ip

您可以使用

npm i express-ip

使用

const express = require('express');
const app = express();
const expressip = require('express-ip');
app.use(expressip().getIpInfoMiddleware);

app.get('/', function (req, res) {
    console.log(req.ipInfo);
});

在nginx.conf文件中: proxy_set_header X-Real-IP $remote_addr;

在node.js服务器文件中: Var IP = req。headers['x-real-ip'] || req.connection.remoteAddress;

注意,表示小写头