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]

更新於:06-Apr-2022

273 次瀏覽

啟動您的 職業

完成課程後可獲得認證

開始
廣告
© . All rights reserved.