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

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

当前回答

在节点10.14中,在nginx后面,你可以通过nginx头请求它来检索ip,就像这样:

proxy_set_header X-Real-IP $remote_addr;

然后在你的app.js中:

app.set('trust proxy', true);

在那之后,你想让它出现的地方:

var userIp = req.header('X-Real-IP') || req.connection.remoteAddress;

其他回答

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

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

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

警告:

不要盲目地将其用于重要的速率限制:

let ip = request.headers['x-forwarded-for'].split(',')[0];

这很容易被欺骗:

curl --header "X-Forwarded-For: 1.2.3.4" "https://example.com"

在这种情况下,用户的真实IP地址将是:

let ip = request.headers['x-forwarded-for'].split(',')[1];

我很惊讶,没有其他答案提到这一点。

在节点10.14中,在nginx后面,你可以通过nginx头请求它来检索ip,就像这样:

proxy_set_header X-Real-IP $remote_addr;

然后在你的app.js中:

app.set('trust proxy', true);

在那之后,你想让它出现的地方:

var userIp = req.header('X-Real-IP') || req.connection.remoteAddress;

Var ipaddress = (req。标题(“x-forwarded-for”)| | req.connection.remoteAddress | | req.socket.remoteAddress | | req.connection.socket.remoteAddress) .split (", ") [0];

也有同样的问题…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;
}