Express.js – req.ips 属性
req.ips 包含 X-Forwarded-For 请求头值中所有 IP 地址的数组。该属性仅在信任代理设置不为 False 时才会填充。该头值或 IP 可以由代理或客户端设置。
语法
req.ips
示例 1
创建一个名为 "reqIps.js" 的文件并复制以下代码段。创建文件后,使用命令 "node reqIps.js" 运行此代码,如下例所示
// req.ips Property Demo Example // Importing the express & cookieParser module var cookieParser = require('cookie-parser'); var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // Defining multiple Endpoint app.get('/api', function (req, res) { console.log("IP's : ", req.ips); res.send(req.ips); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
使用 GET 请求访问如下端点:localhost:3000/api
输出
C:\home
ode>> node reqIps.js Server listening on PORT 3000 IP's : []
示例 2
我们来看另一个示例
// req.ips Property Demo Example // Importing the express & cookieParser module var cookieParser = require('cookie-parser'); var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // Defining multiple Endpoint app.get('/api', function (req, res) { console.log("IP's : ", req.ips); res.send(req.ips); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
输出
逐一访问如下端点
GET 请求 – localhost:3000/api
并设置标头为
x-forwarded-for: 105.0.114.165, 61.91.3.17, 120.192.192.255
C:\home
ode>> node reqIps.js Server listening on PORT 3000 Server listening on PORT 3000 IP's : [105.0.114.165, 61.91.3.17, 120.192.192.255]
广告