简体   繁体   English

在Hapi.js Restful API中了解请求IP

[英]Knowing request IP in Hapi.js Restful API

I'm working on a Restful API with node.js and hapi.js. 我正在使用node.js和hapi.js开发Restful API。 I'm trying to log the IP of the clients that request one of my routes. 我正在尝试记录请求我的一条路线的客户端的IP。

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. 但是当我查看我的日志时, ip是未定义的。 How can I solve my problem? 我怎样才能解决我的问题?

使用request.info.remoteAddress而不是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 comma-separated set of multiple IP addresses in the case where the request passes through multiple proxy servers. 以下是对已接受答案的细化,该答案说明了在请求通过多个代理服务器的情况下,x-forwarded-for标头可以是逗号分隔的多个IP地址集。 In such a scenario the client IP will be the leftmost (first) IP address. 在这种情况下,客户端IP将是最左边(第一个)IP地址。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM