javascript - Knowing request IP in Hapi.js Restful API - Stack Overflow

I'm working on a Restful API with node.js and hapi.js. I'm trying to log the IP of the client

I'm working on a Restful API with node.js and hapi.js. I'm trying to log the IP of the clients that request one of my routes.

This is my current code:

function(request, reply){
    var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
    console.log('IP: ' + ip);

    //more code...
}

But ip is undefined when I watch my logs. How can I solve my problem?

I'm working on a Restful API with node.js and hapi.js. I'm trying to log the IP of the clients that request one of my routes.

This is my current code:

function(request, reply){
    var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
    console.log('IP: ' + ip);

    //more code...
}

But ip is undefined when I watch my logs. How can I solve my problem?

Share Improve this question edited Apr 7, 2015 at 16:36 Alex Salauyou 14.4k5 gold badges47 silver badges69 bronze badges asked Apr 7, 2015 at 16:15 LeoLeo 4592 silver badges17 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Use request.info.remoteAddress instead of request.connection.remoteAddress:

var ip = request.headers['x-forwarded-for'] || request.info.remoteAddress;

Here is a refinement of the accepted answer that accounts for the fact that the x-forwarded-for header can be a ma-separated set of multiple IP addresses in the case where the request passes through multiple proxy servers. In such a scenario the client IP will be the leftmost (first) IP address. This code will handle both possible formats of the header:

var xFF = request.headers['x-forwarded-for'];
var ip = xFF ? xFF.split(',')[0] : request.info.remoteAddress;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744251599a4565194.html

相关推荐

  • javascript - Knowing request IP in Hapi.js Restful API - Stack Overflow

    I'm working on a Restful API with node.js and hapi.js. I'm trying to log the IP of the client

    8天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信