首页 > 解决方案 > 如何从请求nodejs中获取ip

问题描述

我想从发布请求中获取 ip。

var ip = req.ip || req.headers['x-forwarded-for'] || 
req.connection.remoteAddress || 
req.socket.remoteAddress ||
(req.connection.socket ? req.connection.socket.remoteAddress : null)

res.json({
  success: true,
  message: 'ip'+ip
});

但它返回一个null值。我在服务上使用(它不是本地主机)

有什么解决办法吗?所有解决方案都返回null

标签: javascriptnode.js

解决方案


如果它位于像 Nginx 这样的反向代理之后,请尝试使用来自 ngx_http_core_module 的嵌入变量。(至少这就是我现在多年来所做的事情)。

Nginx 配置文件

....
location / {
   proxy_set_header X-Real-IP $remote_addr;
....

节点.js

req.headers["x-real-ip"]

推荐阅读