當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Express.js req.cookies用法及代碼示例

當用戶使用cookie-parser中間件時,將使用req.cookies屬性。此屬性是一個包含請求發送的cookie的對象。

用法:

req.cookies

參數:沒有參數。

返回值:Object

快遞模塊的安裝:



  1. 您可以訪問安裝Express模塊​​的鏈接。您可以使用此命令安裝此軟件包。
    npm install express
  2. 安裝Express模塊​​後,可以使用命令在命令提示符下檢查Express版本。
    npm version express
  3. 之後,您可以僅創建一個文件夾並添加一個文件,例如index.js。要運行此文件,您需要運行以下命令。
    node index.js

範例1: 文件名:index.js

var cookieParser = require('cookie-parser'); 
var express = require('express'); 
var app = express();  
var PORT = 3000; 
  
app.use(cookieParser()); 
  
app.get('/', function (req, res) { 
  req.cookies.title='GeeksforGeeks';   
  console.log(req.cookies); 
  res.send(); 
}); 
  
app.listen(PORT, function(err){ 
    if (err) console.log(err); 
    console.log("Server listening on PORT", PORT); 
});

運行程序的步驟:

  1. 項目結構將如下所示:
  2. 確保使用以下命令安裝了Express和cookie-parser模塊:
    npm install express
    npm install cookie-parser
    
  3. 使用以下命令運行index.js文件:
    node index.js

    輸出:

    Server listening on PORT 3000
    
  4. 現在打開瀏覽器並轉到http://localhost:3000 /,現在您可以在控製台上看到以下輸出:
    Server listening on PORT 3000
    [Object:null prototype] { title:'GeeksforGeeks' }
    

範例2: 文件名:index.js

var cookieParser = require('cookie-parser'); 
var express = require('express'); 
var app = express();  
var PORT = 3000; 
   
app.use(cookieParser()); 
   
app.get('/user', function (req, res) { 
  req.cookies.name='Gourav'; 
  req.cookies.age=12;   
  
  console.log(req.cookies); 
  res.send(); 
}); 
   
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 /user發出GET請求,現在您可以在控製台上看到以下輸出:

Server listening on PORT 3000
[Object:null prototype] { name:'Gourav', age:12 }

參考: https://expressjs.com/en/4x/api.html#req.cookies




相關用法


注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Express.js req.cookies Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。