2015-09-21 58 views
0
{ host: '127.0.0.1:8080', 
    connection: 'keep-alive', 
    'cache-control': 'max-age=0', 
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/44.0.2403.89 Chrome/44.0.2403.89 Safari/537.36', 
    accept: '*/*', 
    referer: 'http://127.0.0.1:8080/', 
    'accept-encoding': 'gzip, deflate, sdch', 
    'accept-language': 'en-US,en;q=0.8', 
    cookie: 'io=bP2eXrqS3SkWYY4cAAAC11' } 

我使用koa.io從NPM嘗試並獲得客戶端連接的IP地址。當我嘗試下面的代碼時,上面的內容被打印在控制檯中。我似乎無法獲得客戶端的IP地址。頭不透露IP地址?

app.io.use(function* userLeft(next) { 
    // on connect 
    console.log(this.headers); 
}); 

我目前在localhost上。所以我期待客戶端IP地址是127.0.0.1?

回答

0

嘗試this.request.ip。它應該工作...

測試後,我意識到兩件事情。

  1. 當代理髮生故障時,請確保代理使用x-forwarded-for標頭轉發客戶端ip。
  2. 理論上1.應該夠this.request.ip返回客戶端IP,但事實並非如此。但在配置我的代理後,this.request.header["x-forwarded-for"]返回客戶端IP

測試這個簡單的服務器:

var koa = require('koa'); 
var app = koa(); 

app.use(function *(){ 
this.body = this.request.ip; 
}); 

app.listen(3000); 
+0

你好試了一下:'的console.log(this.request.ip);',返回undefined:/ –

+0

你是否在身後代理?我在這裏使用nginx,我也沒有得到cleint ip。我必須做兩件事才能讓它正確。在我的服務器nginx配置中,我不得不添加'proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;',然後與文檔「x-forwarded-for」ist不支持,因此我不得不'this.request.header [的x轉發換「]'。我會根據更新的答案... –

+0

你好!我目前只在本地主機上的一切。也許這是問題? –