简体   繁体   English

获取节点的请求hapijs中的客户端IP地址

[英]get client ip address in request hapijs for node

我需要在hapijs节点的请求中使用我的应用程序获取客户端的IP地址...我们使用pm2和Nginx服务器运行实时我们使用了request.info.address但是它给服务器本地ip作为127.0.0.1但我需要的是使用我的应用程序的客户端IP,例如:192.xx111 ...

In case if you are running the server behind a Nginx proxy server you would have to use 如果您在Nginx代理服务器后面运行服务器,则必须使用

    req.headers['x-real-ip']

else you can use 否则你可以使用

req.info.remoteAddress

I always get client IP address with this function :) 我总是用这个函数得到客户端IP地址:)

    return request.headers['x-forwarded-for'] ||
    request.connection.remoteAddress ||
    request.socket.remoteAddress ||
    request.connection.socket.remoteAddress;

Hope it helps. 希望能帮助到你。

I'm running the same stack for my hapi apps with nginx and PM2. 我正在使用nginx和PM2为我的hapi应用程序运行相同的堆栈。 Proxying requests through nginx to a node app on the same host will always result in 127.0.0.1 for the remote address, because nginx forwards the request on the same host. 通过nginx将请求代理到同一主机上的节点应用程序将始终导致远程地址为127.0.0.1 ,因为nginx会在同一主机上转发请求。

Solution: there's a dedicated plugin hapi-geo-locate that determines the actual client IP address even though you're running your app behind a reverse proxy (like nginx). 解决方案:有一个专用插件hapi-geo-locate确定实际的客户端IP地址,即使您在反向代理(如nginx)后运行您的应用程序。

hapi-geo-locate supports various proxies and HTTP headers, so you should be save and get the user's IP running your app on different platforms. hapi-geo-locate支持各种代理和HTTP头,因此您应该保存并获取用户的IP在不同平台上运行您的应用程序。

Hope that helps! 希望有所帮助!

You should check the configuration on the reverse proxy (nginx) and see if you are sending the ip and how you're doing it. 您应该检查反向代理(nginx)上的配置,看看您是否正在发送IP以及您是如何进行的。

For example (nginx conf): 例如(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;
    }
}

In this case, you will get the client's IP via the header X-Real-IP . 在这种情况下,您将通过标头X-Real-IP获取客户端的X-Real-IP

So in HapiJS, where you have access to the request object: 所以在HapiJS中,您可以访问request对象:

const ip = request.headers['x-real-ip'] || request.info.remoteAddress;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM