Express.js – 获取远程客户端地址
应用程序需要维护远程客户端地址,以管理计算机系统的请求数量并跟踪其使用情况。但有时,服务器在 NGINX 服务器后面运行,因此我们需要检查其转发请求。为此,我们可以使用“x-forwarded-for”
语法
req.headers['x-forwarded-for'] || req.socket.remoteAddress
如果此代理不属于您,则在使用x-forwarded-for标头时应小心,因为它可能会被欺骗。
示例 1
创建一个名为“remoteAddress.js”的文件并复制以下代码段。创建文件后,使用命令“node remoteAddress.js”运行此代码,如下例所示 −
// req.query() Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); var PORT = 3000; // Getting the request query string app.get('/api', function(req, res){ console.log('id: ' + req.query.id) res.send('id: ' + req.query.id); }); // Listening to the port app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
在以下端点发出 Get 请求 - https://127.0.0.1:3000/
输出
C:\home
ode>> node remoteAddress.js Server listening on PORT 3000 IP Address: ::ffff:127.0.0.1
示例 2
我们来看另一个示例。
// express.raw() Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); var PORT = 3000; app.get('/api*', function (req, res){ var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress console.log('IP Address: ' + ip) }); // Listening to the port app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); }); app.get('/', function (req, res){ var forwardedIpsStr = req.header('x-forwarded-for'); var IP = ''; if (forwardedIpsStr) { IP = forwardedIps = forwardedIpsStr.split(',')[0]; } });
对以下任何端点发出 Get 请求 –
https://127.0.0.1:3000/api https://127.0.0.1:3000/api/v2 https://127.0.0.1:3000/api/v3 and so on...
它会将所有端点与/api进行比较并跟踪它。
输出
C:\home
ode>> node remoteAddress.js Server listening on PORT 3000 IP Address: ::ffff:127.0.0.1 IP Address: ::ffff:127.0.0.1 IP Address: ::ffff:127.0.0.1
广告