如何在Node.js和Express(和Heroku)应用程序中正确使用ipinfo.io [英] How to use ipinfo.io in Node.js and Express (and Heroku) application properly

查看:77
本文介绍了如何在Node.js和Express(和Heroku)应用程序中正确使用ipinfo.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阻止来自某些特定国家/地区的用户,并发现ipinfo.io达到了目的.但是,当我尝试在Node.js和Express应用程序中使用它时,似乎没有返回正确的结果.

I want to block users from some specific countries, and found that ipinfo.io serves the purpose. But when I tried to use it in my Node.js and Express application, it looks like it didn't return a correct result.

这是我编写的代码:


var request = require("request");

exports.index = function(req, res) {
    request.get("http://ipinfo.io/" + req.ip + "/json", function(err, response, body) {
        res.write(body);
        res.end()
    });
}

exports.index2 = function(req, res) {
    request.get("http://ipinfo.io/json", function(err, response, body) {
        res.write(body);
        res.end();
    });
}

我在每个特定的路线上都说了上述两个功能,例如http://myapp/index1http://myapp/index2.但是,当我尝试访问http://myapp/index1时,结果如下所示:

And I conencted those two functions above to each specific route, say, http://myapp/index1 and http://myapp/index2. However, when I tried to access http://myapp/index1, the result is something like follows:

{
  "ip": "10.xxx.xx.xx", # BTW, is this ip secure information?
  "hostname": "No Hostname",
  "loc": "",
  "bogon": true
}

因此它不会返回正确的值.

So it doesn't return a correct value.

当我尝试访问http://myapp/index2时,结果是AWS上的IP,因为Heroku在后台使用AWS.

When I tried to access http://myapp/index2, the result is an IP on AWS, since Heroku uses AWS in its background.

那么我如何让它返回正确的结果?

So how can I have it return a proper result?

推荐答案

https://devcenter. heroku.com/articles/http-routing 说:

"X-Forwarded-For:连接到Heroku路由器的客户端的原始IP地址"

因此使用:

req.headers['x-forwarded-for']

代替

req.ip

如果使用req.ip,则是在向ipinfo.io询问路由器的IP.

If you use req.ip, you are "asking" ipinfo.io about the IP of the router.

这篇关于如何在Node.js和Express(和Heroku)应用程序中正确使用ipinfo.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆