在节点前使用nginx服务器作为代理时如何获取客户端真实IP

Lia*_*ana 8 ip proxy http node.js express

我需要在 nodeJs 中获取客户端的真实 IP 地址,当使用 nginx 代理服务器时,我总是得到我的 localhost(127.0.0.1)。谁能帮我解决这个问题?这是我的代码

app.set('trust proxy', 'loopback');
app.use(function(req, res, next) {
  app.ipInfo = req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
  next();
});
Run Code Online (Sandbox Code Playgroud)

You*_*neL 8

在 nginx 中,如果要将远程用户的 IP 地址传递到后端 Web 服务器,则必须将X-Forwarded-For标头设置为此远程 ip,如下所示:

proxy_set_header X-Forwarded-For $remote_addr;
Run Code Online (Sandbox Code Playgroud)