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://127.0.0.1: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://127.0.0.1:3000/api
输出
C:\home
ode>> node reqCookies.js Server listening on PORT 3000 [Object: null prototype] { title: 'Mayank', age: 21 }
广告