我不完全明白我应该如何获得一个远程用户IP地址。

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

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

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

上面的方法是否正确,以获得真实的用户IP地址或有更好的方法? 那么代理呢?


当前回答

headers对象有你需要的一切,只需要这样做:

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

其他回答

headers对象有你需要的一切,只需要这样做:

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

添加app.set('信任代理',true) 使用要求。IP或req。Ips和往常一样

这对我来说比其他方法更有效。我的网站在CloudFlare后面,它似乎需要cf- connection -ip。

req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress

没有测试代理后面的Express,因为它没有说任何关于这个cf- connection -ip头。

如果你很好使用第三方库。可以检查request-ip。

你可以用is by

import requestIp from 'request-ip';

app.use(requestIp.mw())

app.use((req, res) => {
  const ip = req.clientIp;
});

源代码很长,所以我就不复制了,你可以在https://github.com/pbojinov/request-ip/blob/master/src/index.js上查看

基本上,

It looks for specific headers in the request and falls back to some defaults if they do not exist. The user ip is determined by the following order: X-Client-IP X-Forwarded-For (Header may return multiple IP addresses in the format: "client IP, proxy 1 IP, proxy 2 IP", so we take the the first one.) CF-Connecting-IP (Cloudflare) Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwared to a cloud function) True-Client-Ip (Akamai and Cloudflare) X-Real-IP (Nginx proxy/FastCGI) X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray) X-Forwarded, Forwarded-For and Forwarded (Variations of #2) req.connection.remoteAddress req.socket.remoteAddress req.connection.socket.remoteAddress req.info.remoteAddress If an IP address cannot be found, it will return null.

公开:我和图书馆没有关系。

var ip = req.connection.remoteAddress;

IP = IP .split(':')[3];