javascript - 如何从请求nodejs获取ip

标签 javascript node.js

我想从post请求中获取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

最佳答案

如果它位于 Nginx 等反向代理后面,请尝试使用 ngx_http_core_module 中的嵌入变量。 (至少这就是我多年来所做的)。

Nginx配置文件

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

Node.js

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

关于javascript - 如何从请求nodejs获取ip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56644999/

相关文章:

javascript - 有什么方法可以让 double 超过 13 位小数吗? C# 还是 JS?

node.js - 使用 Node js imap 读取电子邮件正文

javascript - 如何在 node.js 中使用需要用户名/密码身份验证的 REST api

javascript - Node.js/v8 : How to make my own snapshot to accelerate startup

node.js - 使用 mongoose.js 填充后查询数组

node.js - 了解 Node JS/Node Inspector V8 协议(protocol)

javascript - jQuery点击检测超出指定区域问题

javascript - 将代码包装到 'IF' 语句中更好,还是将函数包装到 'short circuit' 并返回更好?

javascript - 如何使用 node sqlite3 with q (promise)

javascript - 如何检查数组中的对象是否具有参数 ID 中存在的 ID 属性?