如何从控制器内确定给定请求的IP地址?例如(在快递中):

app.post('/get/ip/address', function (req, res) {
    // need access to IP address here
})

当前回答

如果你使用express.js,

app.post('/get/ip/address', function (req, res) {
      res.send(req.ip);
})

其他回答

在nodejs中简单获取远程ip:

var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

也有同样的问题…im也是新的javascript,但我解决了这个与req.connection.remoteAddress;这给了我IP地址(但在ipv6格式::ffff.192.168.0.101),然后.slice删除前7位数字。

var ip = req.connection.remoteAddress;

if (ip.length < 15) 
{   
   ip = ip;
}
else
{
   var nyIP = ip.slice(7);
   ip = nyIP;
}

对于我使用kubernetes ingress (NGINX):

req.headers['x-original-forwarded-for']

在Node.js中非常有效

首先,在项目中安装request-ip

import requestIp from 'request-ip';
const clientIp = requestIp.getClientIp(req); 
console.log(clientIp)

如果使用localhost,结果可能是::1,因为::1是真实的IP地址,是localhost的IPV6表示法。

如果使用express…

req.ip

我在查这个,然后我想,等等,我用的是快递。咄。