2016-11-20 204 views
0

我對NodeJS和它的所有迷人有點新鮮。我試圖弄清楚如何結合geoip-literequest-ip npm軟件包來獲取我的應用的大致用戶位置。Nodejs客戶端IP

到目前爲止,我有這個

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; 

我無法找出使用請求IP來獲得IP。 geoip-lite非常容易,花了2分鐘。我想我對Nodejs的noobness也沒有幫助。一個代碼示例,告訴我我在做什麼錯誤或沒有想到會很好。

+0

你用什麼URL來測試?是偶然的,就像'http:// localhost:3000 /'? – Sgnl

回答

0

我認爲問題是您向服務器發送請求的方式如何

對於你的測試,如果你使用像http://localhost:3000一個網址,然後你會得到::1

但是,如果嘗試,而不是http://127.0.0.1:3000,那麼你可能會得到的IP地址:::ffff:127.0.0.1

這裏的快車代碼我用來測試和我用郵遞員應用程序發出請求

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