Node.js、Express框架获取客户端IP地址

时间:2024-01-21 16:00:29

Node.js

//传入请求HttpRequest
function getClientIp(req) {
return req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
}

Express

//express框架则简单许多
req.ip

意外收获

发现这两种方式获取的ip地址都带有前缀,不知为何,看了眼Express request.js源码,没找到不对的地方。所以用正则表达式处理了下

req.ip.match(/\d+\.\d+\.\d+\.\d+/)