Express.js:如何获取远程客户端地址 [英] Express.js: how to get remote client address

查看:164
本文介绍了Express.js:如何获取远程客户端地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不完全明白我应该如何获取远程用户的IP地址。

I don't completely understand how I should get a remote user IP address.

假设我有一个简单的请求路由,例如:

Let's say I have a simple request route such as:

app.get(/, function (req, res){
   var forwardedIpsStr = req.header('x-forwarded-for');
   var IP = '';

   if (forwardedIpsStr) {
      IP = forwardedIps = forwardedIpsStr.split(',')[0];  
   }
});

上述方法是否正确获取真实用户IP地址或有更好的方法?
代理如何?

Is the above approach correct to get the real user IP address or is there a better way? And what about proxies?

推荐答案

如果您正在运行NGiNX等代理服务器,你应该检查'x-forwarding-for':

If you are running behind a proxy like NGiNX or what have you, only then you should check for 'x-forwarded-for':

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

如果代理不是'你的',我不会相信'x-为'标题,因为它可以被欺骗。

If the proxy isn't 'yours', I wouldn't trust the 'x-forwarded-for' header, because it can be spoofed.

这篇关于Express.js:如何获取远程客户端地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆