【问题标题】:Return ip address of site visitors instead of Heroku server返回站点访问者的 IP 地址而不是 Heroku 服务器
【发布时间】:2021-06-06 14:46:01
【问题描述】:

所以我试图在 Haruko 上获取我的应用程序的访问者的 IP 地址,我为此使用了一个 API,该 API 在本地运行良好,但是当我在 Heroku 上部署应用程序时,我得到了 Heroku 服务器的 IP,它是一个 express.js 应用程序,并且正在使用此设置

app.set('trust proxy', true);

我已经看到了很多解决这个问题的方法,但知道对我有用。

当我使用时

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

我得到了这个结果

clientIp: '::1',

【问题讨论】:

  • 是的,你是从服务器获取的,当然是返回服务器IP...
  • 那我该怎么办? @SuperStormer
  • 这能回答你的问题吗? Express.js: how to get remote client address
  • 我没有得到预期的结果@SuperStormer 我得到 ::1

标签: javascript node.js express heroku


【解决方案1】:

首先你必须安装这个模块npm i ipware

var get_ip = require('ipware')().get_ip;


app.use(function(req, res, next) {
    var ip_info = get_ip(req);
    console.log(ip_info);
    // { clientIp: '127.0.0.1', clientIpRoutable: false }
    next();
});

请注意,结果是对象形式,获取 ipaddress 应该很简单

ip_info.clientIp

所以我想这应该会有所帮助。

【讨论】:

    【解决方案2】:
    var ip = req.headers['x-forwarded-for'] || 
         req.connection.remoteAddress || 
         req.socket.remoteAddress ||
         (req.connection.socket ? req.connection.socket.remoteAddress : null);
    

    但有时您可以通过此 req.headers['x-forwarded-for']

    获得多个 IP 地址
          var ipAddr = req.headers["x-forwarded-for"];
          if (ipAddr){
            var list = ipAddr.split(",");
            ipAddr = list[list.length-1];
          } else {
            ipAddr = req.connection.remoteAddress;
          }
    

    如果没有,您可以使用基本控制。

    或者您可以使用这个并在答案顶部替换为 req.headers['x-forwarded-for']

    let ip = request.headers['x-forwarded-for'].split(',')[0]
    

    【讨论】:

    • 感谢您的解决方案,但我只返回 ::1 而不是 IP 地址
    猜你喜欢
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2015-06-21
    • 2019-10-22
    • 2019-01-12
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多