Express.js 中的 req.cookies 屬性


req.cookies 包含使用 cookie-parser 中介軟體時所傳送的 cookies。如果 cookies 已簽名,請使用 req.signedCookies 屬性。

語法

req.cookies

安裝 cookie-parser 模組 −

npm install cookie-parser

示例 1

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

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

示例 2

我們再來看一個例子。

// req.cookies() 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 endpoint
app.get('/api', function (req, res) {
   req.cookies.name='Mayank';
   req.cookies.age=21;
   console.log(req.cookies);
   res.send();
});
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 reqCookies.js Server listening on PORT 3000 [Object: null prototype] { title: 'Mayank', age: 21 }

更新於: 2022 年 1 月 29 日

2K+ 次瀏覽

開啟您的職業生涯

完成課程並獲得認證

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