admin管理员组文章数量:1401783
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;
本文标签: javascriptKnowing request IP in Hapijs Restful APIStack Overflow
版权声明:本文标题:javascript - Knowing request IP in Hapi.js Restful API - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744251599a2597276.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论