Express.js 中的 res.cookie() 方法


**res.cookie()** 方法用於將 cookie 名稱設定為值。value 引數可以是字串或轉換為 JSON 的物件。

語法

res.cookie( name, value, [options] )

引數

options 引數可以具有以下值:

  • **domain** - 表示 cookie 的域名。預設指的是應用程式的域名。

  • **encode** - 此引數用於在非同步函式中對 cookie 值進行編碼。

  • **expires** - 此引數以 GMT 格式定義 cookie 的過期時間。預設值為 0,這將建立一個會話 cookie。

  • **httpOnly** - 此布林引數將 cookie 標記為僅供 Web 伺服器使用。

  • **maxAge** - 此引數表示一個方便的選項,用於以毫秒為單位設定相對於當前時間的過期時間。

  • **path** - 這是儲存 cookie 的路徑。預設值為“/”。

  • **secure** - 這將 cookie 標記為僅與 https 一起使用。

  • **signed** - 這指示 cookie 是否應該被簽名。

示例

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

// res.cookie(name, value, [options]) Method 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){
   // Setting the below key-value pair
   res.cookie('name', 'tutorialsPoint');
   res.send("Cookies are set");
});
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 resCookie.js Server listening on PORT 3000 Cookies are set

更新於: 2022-01-29

7K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.