Express.js - req.ip 屬性
req.ip 包含了請求收到的遠端 IP 地址。如果信任代理設定沒有設定為 False,則此屬性的值取自 x-forwarded-for 標頭中的最左項。標頭由客戶端或代理設定。
語法
req.ip
示例 1
建立一個名為 "reqIp.js" 的檔案,並將以下程式碼片段複製進去。建立完檔案後,使用命令 "node reqIp.js" 執行此程式碼,如下面的示例所示 −
// req.ip 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 an Endpoint
app.get('/api', function (req, res) {
console.log("IP : ", req.ip);
res.send(req.ip);
});
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 reqIp.js Server listening on PORT 3000 IP : ::ffff:127.0.0.1
示例 2
我們來看另外一個示例。
// req.ip 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;
// Enabling trust proxy
app.enable('trust proxy')
// Defining an Endpoint
app.get('/api', function (req, res) {
console.log("IP : ", req.ip);
res.send(req.ip);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});輸出
依次訪問以下端點 −
GET 請求 – localhost:3000/api
並設定以下標頭 −
x-forwarded-header – 103.0.113.165
C:\home
ode>> node reqIp.js Server listening on PORT 3000 IP : 103.0.113.165
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP