Express.js 中的 req.hostname 屬性


req.hostname 包含源自主機 HTTP 標頭的 hostname。當信任設定屬性已啟用(或未設定為 false)時,此屬性將從 X-Forwarded-Host 標頭欄位獲取其值。此標頭可以由客戶端或代理設定。

如果請求中存在多個 X-Forwarded-Host 標頭,則使用第一個標頭的值。

語法

req.hostname

示例 1

建立一個檔案,名稱為 "reqHostname.js",複製以下程式碼片段。建立檔案後,使用如下示例中所示命令 "node reqHostname.js" 執行此程式碼 −

// req.hostname Property Demo Example

// Importing the express
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(req.hostname);
   res.send(req.hostname);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

用 GET 請求訪問以下端點 − https://:3000/api

輸出

C:\home
ode>> node reqHostname.js Server listening on PORT 3000 localhost

示例 2

我們來看另一個示例。

// Importing the express
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(req.hostname);
   res.send(req.hostname);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

用 GET 請求訪問以下端點 −

  • https://:3000/api

並設定標頭為 −

  • 主機 − tutorialspoint.com

輸出

C:\home
ode>> node reqHostname.js Server listening on PORT 3000 tutorialspoint.com

更新於:2022 年 1 月 29 日

2K+ 檢視

開啟你的 職業

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.