Express.js – req.signedCookies 屬性


req.signedCookies 包含使用 cookie-parser 中介軟體時請求傳送的經過簽名的 Cookie(隨時可用)。已簽名的 Cookie 存在於不同的物件中以便表示開發人員意圖,否則對相對容易欺騙的 request.cookie 值進行惡意攻擊。

如果沒有傳送 Cookie,則屬性的預設值將設定為 "{ }"

語法

req.signedCookies

安裝 cookie-parser 模組

npm install cookie-parser

示例 1

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

// req.signedCookies() Method 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 the cookieParser to be used
app.use(cookieParser());

// Defining an api endpoint
app.get('/api', function (req, res) {
   req.signedCookies.title='TutorialsPoint';
   console.log(req.signedCookies);
   res.send();
});
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 reqSignedCookies.js Server listening on PORT 3000 [Object: null prototype] { title: 'TutorialsPoint' }

示例 2

我們來看另一個示例。

// req.signedCookies() Method 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 the cookieParser to be used
app.use(cookieParser());

// Defining an api endpoint
app.get('/api', function (req, res) {
   // Setting multiple cookies
   req.signedCookies.title='Mayank';
   req.signedCookies.age=21;
   console.log(req.signedCookies);
   res.send();
});

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 reqSignedCookies.js Server listening on PORT 3000 [Object: null prototype] { title: 'Mayank', age: 21 }

更新於:06-Apr-2022

246 次瀏覽

啟動您的職業生涯

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.