获取客户端ip地址请求hapijs中的节点
我需要在hapijs节点的请求中使用我的应用程序获取客户端的IP地址…我们使用pm2和Nginx作为服务器来运行,我们使用了request.info.address,但是它将服务器的本地IP作为127.0.0.1,但我需要的是客户的IP使用我的应用程序,例如:192.xx111 …
我总是得到这个function的客户端IP地址:)
return request.headers['x-forwarded-for'] || request.connection.remoteAddress || request.socket.remoteAddress || request.connection.socket.remoteAddress;
希望能帮助到你。
我使用nginx和PM2为我的hapi应用程序运行相同的堆栈。 通过nginx向同一主机上的节点应用程序请求代理将始终为远程地址127.0.0.1
,因为nginx在同一主机上转发请求。
解决scheme:即使您在反向代理(如nginx)后面运行应用程序,也有一个专用的插件hapi-geo-locate ,用于确定实际的客户端IP地址。
hapi-geo-locate支持各种代理和HTTP标头,所以你应该保存并获得用户的IP在不同的平台上运行你的应用程序。
希望有所帮助!
如果你在Nginx代理服务器后面运行服务器,你将不得不使用
req.headers['x-real-ip']
否则你可以使用
req.info.remoteAddress
你应该检查反向代理(nginx)上的configuration,看看你是否发送的IP,你是怎么做的。
例如(nginx conf):
server { listen 0.0.0.0:80; server_name [your_domain]; root /webroot/[your_domain or webapp name]; access_log /var/log/nginx/[your_domain or webapp name].log; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header HOST $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:[port assigned to node]; proxy_redirect off; } }
在这种情况下,您将通过标题X-Real-IP
获取客户端的X-Real-IP
。
因此,在HapiJS中,您可以访问request
对象:
const ip = request.headers['x-real-ip'] || request.info.remoteAddress;