Express.js 中 req.protocol 屬性
req.protocol 屬性返回請求協議字串,該字串要麼是 http,要麼是(對於 TLS 請求)https。如果存在,將使用 X-Forwarded-Proto 標頭欄位的值,前提是傳遞的信任代理設定不為 False。此標頭值可以由客戶端或代理設定。
語法
req.protocol
示例 1
建立一個名為 "reqProtocol.js" 的檔案,並複製以下程式碼段。建立檔案後,使用命令 "node reqProtocol.js" 執行此程式碼,如下例所示 −
// req.protocol Property Demo Example
// Importing the express module
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("Request Protocol received is: ", req.protocol);
res.send(req.protocol);
});
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 reqProtocol.js Server listening on PORT 3000 Request Protocol received is: http
示例 2
我們再來看看另一個示例。
// req.protocol Property Demo Example
// Importing the express module
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 settings
app.enable('trust proxy');
// Defining an endpoint
app.get('/api', function (req, res) {
console.log("Request Protocol received is: ", req.protocol);
res.send(req.protocol);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 請求點選以下終結點 −
localhost:3000/api
並設定以下標頭 −
- X-Forwarded-Proto = https
輸出
C:\home
ode>> node reqProtocol.js Server listening on PORT 3000 Request Protocol received is: https
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP