如何从控制器内确定给定请求的IP地址?例如(在快递中):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
如何从控制器内确定给定请求的IP地址?例如(在快递中):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
当前回答
首先,在项目中安装request-ip
import requestIp from 'request-ip';
const clientIp = requestIp.getClientIp(req);
console.log(clientIp)
如果使用localhost,结果可能是::1,因为::1是真实的IP地址,是localhost的IPV6表示法。
其他回答
如果您使用的是快速版3。X或更大,您可以使用信任代理设置(http://expressjs.com/api.html#trust.proxy.options.table),它将遍历X -forward -for报头中的地址链,并将链中尚未配置为受信任代理的最新IP放入req对象的IP属性中。
在nodejs中简单获取远程ip:
var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
在节点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;
对于我使用kubernetes ingress (NGINX):
req.headers['x-original-forwarded-for']
在Node.js中非常有效
获取ip地址有两种方式:
让IP = req.ip 让ip = req.connection.remoteAddress;
但上述方法存在一个问题。
如果你在Nginx或任何代理程序后面运行你的应用程序,每个IP地址将是127.0.0.1。
因此,获取user的ip地址的最佳方案是:-
let ip = req.header('x-forwarded-for') || req.connection.remoteAddress;