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 badges2 Answers
Reset to default 7Use 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
评论列表(0条)