How to use ipinfo.io in Node.js and Express (and Heroku) application properly

为君一笑 提交于 2021-01-27 23:49:34

问题


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.

Here's the code that I wrote:


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();
    });
}

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.

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?


回答1:


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

"X-Forwarded-For: the originating IP address of the client connecting to the Heroku router"

So use:

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

instead of

req.ip

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




回答2:


It looks like you're behind a proxy, and you're passing an internal IP address to ipinfo.io. You should enable the "trust proxy" setting so that express pulls the correct IP from the X-Forwarded-For header, eg:

app.enable('trust proxy')

And then you can use req.ip will correctly return the client's IP. You probably shouldn't use req.headers['x-forwarded-for'] directly because that could contain a list of IPs.

More details are available at http://expressjs.com/guide.html#proxies



来源:https://stackoverflow.com/questions/22670810/how-to-use-ipinfo-io-in-node-js-and-express-and-heroku-application-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!