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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP