res.cookie()函數用於將cookie名稱設置為value。 value參數可以是字符串或轉換為JSON的對象。
用法:
res.cookie(name, value [, options])
參數:name參數保存cookie的名稱,value參數是分配給cookie名稱的值。 options參數包含各種屬性,例如編碼,過期,域等。
返回值:它重新調整對象。
快遞模塊的安裝:
- 您可以訪問安裝Express模塊的鏈接。您可以使用此命令安裝此軟件包。
npm install express
- 安裝Express模塊後,可以使用命令在命令提示符下檢查Express版本。
npm version express
- 之後,您可以僅創建一個文件夾並添加一個文件,例如index.js。要運行此文件,您需要運行以下命令。
node index.js
範例1: 文件名:index.js
var express = require('express');
var app = express();
var PORT = 3000;
// Without middleware
app.get('/', function(req, res){
// key-value
res.cookie('name', 'geeksforgeeks');
res.send("Cookie Set");
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
運行程序的步驟:
- 項目結構將如下所示:
- 確保使用以下命令安裝了Express模塊:
npm install express
- 使用以下命令運行index.js文件:
node index.js
輸出:
Server listening on PORT 3000
- 打開瀏覽器並轉到http://localhost:3000 /,現在您在屏幕上看到以下輸出:
Cookie Set
範例2: 文件名:index.js
var express = require('express');
var app = express();
var PORT = 3000;
// With middlware
app.use('/', function(req, res, next){
res.cookie('title', 'GeeksforGeeks');
res.send("Cookie Set");
next();
})
app.get('/', function(req, res){
console.log('Cookie SET');
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
使用以下命令運行index.js文件:
node index.js
現在打開瀏覽器並轉到http://localhost:3000 /,現在檢查控製台,您將看到以下輸出:
Server listening on PORT 3000 Cookie SET
您將在瀏覽器中看到以下輸出:
Cookie Set
參考: https://expressjs.com/en/5x/api.html#res.cookie
相關用法
- PHP Ds\Map get()用法及代碼示例
- PHP Ds\Set add()用法及代碼示例
- PHP dir()用法及代碼示例
- PHP Ds\Set last()用法及代碼示例
- CSS rgb()用法及代碼示例
- PHP Ds\Set contains()用法及代碼示例
- PHP Ds\Set first()用法及代碼示例
- p5.js nfp()用法及代碼示例
- p5.js nfs()用法及代碼示例
- p5.js value()用法及代碼示例
- PHP Ds\Map xor()用法及代碼示例
- PHP Ds\Map put()用法及代碼示例
- PHP Ds\Set xor()用法及代碼示例
注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Express.js res.cookie() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。