如何从控制器内确定给定请求的IP地址?例如(在快递中):

app.post('/get/ip/address', function (req, res) {
    // need access to IP address here
})

当前回答

我试过了,但都没用,

console.log(clientIp);
console.log(req.ip);

console.log(req.headers['x-forwarded-for']);
console.log(req.connection.remoteAddress);
console.log(req.socket.remoteAddress);
console.log(req.connection.socket.remoteAddress.split(",")[0]);

当在Nginx代理后运行Express应用程序时,你必须将应用程序变量信任代理设置为true。Express提供了其他一些信任代理值,您可以在它们的文档中查看这些值,但以下步骤对我来说是有效的。

app.set('trust proxy', true)

App.set('信任代理',true);

在Nginx中添加proxy_set_header X-Forwarded-For $remote_addr 服务器块的配置。

位置/ { proxy_pass http://localhost: 3001; proxy_http_version 1.1; 升级$http_upgrade; 连接“升级”; 主机$ Host; proxy_set_header X-Forwarded-For $remote_addr;#这一行 proxy_cache_bypass http_upgrade美元; }

对象中读取客户端的IP地址 req.header('x-forwarded-for')或req.connection.remoteAddress;ipfilter的完整代码

module.exports = function(req, res, next) { let enable = true; // true/false let blacklist = ['x.x.x.x']; let whitelist = ['x.x.x.x']; let clientIp = req.header('x-forwarded-for') || req.connection.remoteAddress; if (!clientIp) { return res.json('Error'); } if (enable && paths.some((path) => (path === req.originalUrl))) { let blacklist = blacklist || []; if (blacklist.some((ip) => clientIp.match(ip) !== null)) { return res.json({ status: 401, error: 'Your IP is black-listed !'}); } let whitelist = whitelist || []; if (whitelist.length === 0 || whitelist.some((ip) => clientIp.match(ip) !== null)) { next(); return; } else { return res.json({ status: 401, error: 'Your IP is not listed !'}); } } next(); };

其他回答

获取ip地址有两种方式:

让IP = req.ip 让ip = req.connection.remoteAddress;

但上述方法存在一个问题。

如果你在Nginx或任何代理程序后面运行你的应用程序,每个IP地址将是127.0.0.1。

因此,获取user的ip地址的最佳方案是:-

let ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

函数getCallerIP(请求){ Var IP = request。标题(“x-forwarded-for”)| | request.connection.remoteAddress | | request.socket.remoteAddress | | request.connection.socket.remoteAddress; IP = IP .split(',')[0]; IP = IP .split(':').slice(-1);//如果IP以“::ffff:146.xxx.xxx.xxx”格式返回 返回的ip; }

你可以像这样快速获取用户Ip

req.ip

在这个例子中,我们获取了用户的Ip,然后用req.ip把它发回给用户

app.get('/', (req, res)=> { 
    res.send({ ip : req.ip})
    
})

Var ipaddress = (req。标题(“x-forwarded-for”)| | req.connection.remoteAddress | | req.socket.remoteAddress | | req.connection.socket.remoteAddress) .split (", ") [0];

在Typescript中使用ValidatorJS。下面是NodeJS中间件:

// Extract Client IP Address
app.use((req, res, next) => {
    let ipAddress = (req.headers['x-forwarded-for'] as string || '').split(',')[0]
    if (!validator.isIP(ipAddress))
        ipAddress = req.socket.remoteAddress?.toString().split(':').pop() || ''
    if (!validator.isIP(ipAddress))
        return res.status(400).json({errorMessage: 'Bad Request'})

    req.headers['x-forwarded-for'] = ipAddress
    next()
})

在这里,我假设所有请求都应该有一个有效的IP地址,因此如果没有找到有效的IP地址,则返回一个代码为400的响应。