Express.js – req.secure 屬性


req.secure 屬性返回一個布林值,如果建立了 TLS 連線,則返回真;否則,將返回假。

其邏輯類似於以下方法 −

--> req.protocol == "https"

語法

req.secure

示例 1

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

// req.secure 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.secure);
   res.end(req.secure);
});

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 reqSecure.js Server listening on PORT 3000 false

示例 2

我們再看一個示例。

// req.secure 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) {
   if (req.secure) {
      console.log("Secured Connection")
      res.end();
   } else {
      console.log("Connection is Not Secured");
      res.end();
   }
});

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 reqSecure.js Server listening on PORT 3000 Connection is Not Secured

更新時間:2022-03-28

189 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.