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

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

当前回答

请求。headers['x-forwarded-for'] || request.connection.remoteAddress . headers['x-forwarded-for'

如果有x-forward -for报头,则使用它,否则使用. remoteaddress属性。

The x-forwarded-for header is added to requests that pass through load balancers (or other types of proxy) set up for HTTP or HTTPS (it's also possible to add this header to requests when balancing at a TCP level using proxy protocol). This is because the request.connection.remoteAddress the property will contain the private IP address of the load balancer rather than the public IP address of the client. By using an OR statement, in the order above, you check for the existence of an x-forwarded-for header and use it if it exists otherwise use the request.connection.remoteAddress.

其他回答

获取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;
var ip = req.headers['x-forwarded-for'] ||
     req.socket.remoteAddress ||
     null;

请注意,有时您可以在req.headers['x-forwarded-for']中获得多个IP地址。此外,并不总是设置x-forward -for报头,这可能会抛出错误。

该字段的一般格式为:

x-forward -for: client, proxy1, proxy2, proxy3

其中的值是一个逗号+空格分隔的IP地址列表,最左边是原始客户端,每个传递请求的后续代理添加接收请求的IP地址。在本例中,请求通过proxy1、proxy2和proxy3传递。Proxy3显示为请求的远程地址。

这是Arnav Gupta提出的解决方案,Martin在下面的评论中为未设置x-forward -for的情况提出了修复建议:

var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() || 
         req.socket.remoteAddress

使用现代JS的建议:

仅在设置时处理x-forward -for,如果设置了,则取第一个地址 其他参数使用可选链接(?.)

const parseIp = (req) =>
    req.headers['x-forwarded-for']?.split(',').shift()
    || req.socket?.remoteAddress

console.log(parseIp(req))
// => 127.0.0.1

在你的请求对象中有一个属性叫socket,它是一个网络。套接字对象。净。套接字对象有一个属性remoteAddress,因此你应该能够通过这个调用得到IP:

request.socket.remoteAddress

(如果您的节点版本低于13,请使用已弃用的request.connection.remoteAddress)

EDIT

正如@juand在评论中指出的那样,如果服务器位于代理之后,获得远程IP的正确方法是request.headers['x-forwarded-for']

编辑2

在Node.js中使用express时:

如果你设置了app.set('信任代理',true),请请求。ip将返回真实ip地址,即使在代理。查看文档了解更多信息

我在nginx后面使用express和

req.headers.origin

对我有用吗

你可以像这样快速获取用户Ip

req.ip

在这个例子中,我们获取了用户的Ip,然后用req.ip把它发回给用户

app.get('/', (req, res)=> { 
    res.send({ ip : req.ip})
    
})