【问题标题】:get client ip address in request hapijs for node在请求 hapijs 中获取节点的客户端 IP 地址
【发布时间】:2017-10-19 06:31:44
【问题描述】:

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

【问题讨论】:

标签: javascript node.js hapijs


【解决方案1】:

您应该检查反向代理 (nginx) 上的配置,看看您是否发送了 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 获取客户端的IP。

所以在 HapiJS 中,您可以访问 request 对象:

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

【讨论】:

    【解决方案2】:

    如果您在 Nginx 代理服务器后面运行服务器,则必须使用

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

    你也可以使用

    req.info.remoteAddress
    

    【讨论】:

    • 我试过这个兄弟,但仍然返回 Undefined 我需要在我的 ajax 中添加任何额外的标头功能来获取我的处理程序中的 ip 还是有任何特殊的方法来获取Hapi.Js 的 req 中的 IP,因为我浏览的所有答案大多是 express.js
    • 最好控制您的请求/标头/连接对象并查看哪些所有属性都可用。 Request.info 适用于 hapi,但您可能想检查整个请求对象以了解它为什么不起作用,或者您可以在此处发布您的请求对象以供所有人检查。
    【解决方案3】:

    我总是用这个函数获取客户端 IP 地址 :)

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

    希望对你有帮助。

    【讨论】:

    • 对不起兄弟@Sparw 我已经尝试过这些,结果如下: req.headers['x-forwarded-for'] => 'undefined' request.connection.remoteAddress || request.socket.remoteAddress || request.connection.socket.remoteAddress => 这些东西抛出错误 'Debug: internal, implementation, error TypeError: Uncaught error: Cannot read property 'remoteAddress' of undefined '
    • 也许你必须用“req”替换所有“request”?
    【解决方案4】:

    我正在使用 nginx 和 PM2 为我的 hapi 应用程序运行相同的堆栈。通过 nginx 将请求代理到同一主机上的节点应用程序将始终导致远程地址为127.0.0.1,因为 nginx 在同一主机上转发请求。

    解决方案:有一个专用插件hapi-geo-locate 可以确定实际的客户端 IP 地址,即使您在反向代理(如 nginx)后面运行应用程序也是如此。

    hapi-geo-locate 支持各种代理和 HTTP 标头,因此您应该保存并获取用户的 IP 在不同平台上运行您的应用程序。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 2013-03-31
      • 2018-08-21
      • 1970-01-01
      • 2019-01-14
      相关资源
      最近更新 更多