routerjs中怎么获取cookie
在router.js中获取cookie可以使用req.cookies属性。这个属性是通过cookie-parser中间件解析请求头中的cookie得到的,因此在使用前需要先安装和配置cookie-parser。
安装和配置cookie-parser:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// 配置cookie-parser中间件
app.use(cookieParser());
使用req.cookies获取cookie:
app.get('/', (req, res) => {
const cookieValue = req.cookies.myCookie;
console.log(cookieValue);
res.send('Hello World');
});
在这个例子中,我们通过req.cookies获取了名为myCookie的cookie的值,并将其打印到控制台中。如果请求头中没有myCookie这个cookie,cookieValue的值将为undefined。
原文地址: https://www.cveoy.top/t/topic/8co 著作权归作者所有。请勿转载和采集!