使用Node.js,怎样获取到用户的IP地址
发布网友
发布时间:2022-04-21 17:56
我来回答
共1个回答
热心网友
时间:2023-07-09 03:08
因为涉及兼容性问题,可以通过req.header('x-forwarded-for')与req.connection.remoteAddress来获取IP地址,下面是封装好的一个函数:
function getClientIp(req) {
var ipAddress;
var forwardedIpsStr = req.header('x-forwarded-for');
if (forwardedIpsStr) {
var forwardedIps = forwardedIpsStr.split(',');
ipAddress = forwardedIps[0];
}
if (!ipAddress) {
ipAddress = req.connection.remoteAddress;
}
return ipAddress;
};