Nodejs客户端IP

时间:2016-11-20 01:25:43

标签: node.js

我对NodeJS有点新鲜,而且它的所有功能都很棒。我试图找出如何合并geoip-literequest-ip npm包以获取应用的大致用户位置。

到目前为止,我有这个

    var requestIp = require('request-ip');
var geoip = require('geoip-lite');
var express = require('express');
var app = express();

//var ip = "108.219.41.178";//207.97.227.239
//var ip = req.headers['x-real-ip'] || req.connection.remoteAddress;
//var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

var ip = ???

var geo = geoip.lookup(ip);

var port = process.env.PORT || 3000;

/*app.use('/', function(req, res, next) {
    var ipMiddleware = function(req, res, next) {
    var clientIp = requestIp.getClientIp(req); 
    next();
    };
});*/

app.get('/', function(req, res) {
    res.send('<html><head><head/><body><h1>Hello World!</h1></body></html');
});


app.listen(port, function () {
    console.log('Hello on 3000');/*always put console.log to see if its running/working*/
    console.log(geo);
    console.log("The IP is %s", geoip.pretty(ip));
});

/*node app.js to run*/

// var ip = req.headers['x-real-ip'] || req.connection.remoteAddress;

我无法确定使用request-ip获取IP。 geoip-lite非常简单,耗时2分钟。我想我对Nodejs的无知也没有帮助。一个代码示例向我展示我做错了什么或者没想到会很棒。

1 个答案:

答案 0 :(得分:0)

我认为问题是如何您向服务器发出请求。

对于您的测试,如果您使用http://localhost:3000之类的网址,那么您将获得::1

但是,如果尝试改为http://127.0.0.1:3000,那么您可能会获得IP地址:::ffff:127.0.0.1

这是我用来测试的Express代码,我使用Postman App发出请求

const Express = require('express');
const App = Express();

App.get('/', (req, res) => {
  var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress;
  res.send({ ip })
});

App.listen(3000);