Node / Express.js:涉及代理时获取客户端IP地址

时间:2019-03-06 23:48:09

标签: node.js express proxy http-headers ip-address

我是Node and Express的新手。我正在尝试检索客户端IP地址。

我尝试使用以下内容:

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

我的完整get功能如下:

app.get("/api/whoami", function (req, res) {
  var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  res.json({
    ipaddress: ip
  });
});

ipaddress不显示客户端的完整IP地址,而是显示以下内容:

"ipaddress":"::1"

为什么IP地址显示为::1?我了解这可能是由于使用了代理并且Express具有built in solutions for dealing with trusting proxies。该文档说使用这样的东西:

app.set('trust proxy', 'loopback')

我已经尝试了Express文档中的所有变体,但无法获得正确的IP地址。

如何正确设置Express服务器以允许我检索真实IP地址而不是::1

0 个答案:

没有答案