node.js从http请求对象获取客户端IP

Fos*_*tah 3 javascript node.js

如何从http req对象获取客户端IP地址?

IE:

   var util = require('util'),
    colors = require('colors'),
    http = require('http'),
    httpProxy = require('../../lib/node-http-proxy');

//
// Http Server with proxyRequest Handler and Latency
//
var proxy = new httpProxy.RoutingProxy();
http.createServer(function (req, res) {
  // GET IP address here
  // var ip = ??
  var buffer = httpProxy.buffer(req);
  setTimeout(function () {
    proxy.proxyRequest(req, res, {
      port: 9000,
      host: 'localhost',
      buffer: buffer
    });
  }, 200);
}).listen(8004);
Run Code Online (Sandbox Code Playgroud)

小智 7

它应该是 req.connection.remoteAddress


Tim*_*ade 5

这通常是获取客户端IP地址的正确位置,但并非总是如此.如果您在node.js前使用Nginx,Apache或其他反向代理,则可能必须从req.headers获取IP地址.具有远程IP地址的标头的通用名称包括"X-Remote-IP"或"X-Originating-IP",但不同的服务器使用不同的标头名称.