在 Router.js 中获取 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/mxfr 著作权归作者所有。请勿转载和采集!