使用Express,我有以下设置:
所以当我访问
const express = requires("express");
const path = requires("path");
const bodyParser = requires("body-parser");
const cookieParser = requires("cookie-parser");
let server = express();
server.set("port", (process.env.PORT || 5000));
server.set("views", path.join(__dirname, "/views"));
server.set("view engine", "ejs");
server.use(cookieParser());
server.use(express.static(self.workingDirectory + "/public"));
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.use((req, res, next) => {
// if req.cookies exists and testcookie is undefined within req.cookies
if ( req.cookies && typeof req.cookies["testcookie"] === "undefined" ) {
console.log("Setting cookie! Testcookie was not found");
res.cookie("testcookie", "test", {
maxAge : ((((1000*60)*60)*24)*7), /* expire a week from today */
httpOnly: true /* document.cookie doesn't return this cookie */
});
}
next();
});
server.get("/", (req, res) => { res.render("pages/index"); });
server.listen(server.get("port"), () => { console.log("Server started!"); });
所以当我访问
/
时,cookie会被设置为适当的值,但在之后的每次访问中,它仍然会被设置。稍后当我通过新的中间件运行console.log(req.headers)
时,在访问/
时每次都会显示以下内容,尽管cookie应该已经被设置:
响应头中包含了cookie:
我在这里做错了什么吗?我弄不清楚问题出在哪里... cookie-parser
不是应该用来将 req.headers.cookie
中的 cookie 填充到 req.cookies
中吗?为什么 req.headers.cookie
返回为空?如果我注释掉与 cookie-parser
有关的任何内容,req.headers.cookie
也会返回空。