javascript - 在 Nodejs 中设置 cookie
问题描述
我正在做一个小型请愿项目,我想在用户签名时设置一个 cookie,所以如果他再次尝试访问该页面,它应该已经将他重定向到“感谢页面”。如果用户没有,那么他可以继续签名。我得到了Cannot set headers after they are sent to the client
错误,也许有人明白我做错了什么。在 js 代码下方。
const express = require("express");
const { getSignatures, addSignature } = require("./db.js");
const app = express();
const cookieParser = require("cookie-parser");
app.use(express.urlencoded({ extended: false }));
app.use(express.static("./public"));
const hb = require("express-handlebars");
app.engine("handlebars", hb());
app.set("view engine", "handlebars");
app.use(cookieParser());
app.get("/", (req, res) => {
res.redirect("/petition");
});
app.get("/petition", (req, res) => {
let hasSigned = req.cookies.petition_signed;
if (!hasSigned) {
res.render("petition", {
layout: "main",
});
} else {
res.redirect("/thanks");
}
});
app.post("/petition", (req, res) => {
const { firstName, lastName, signature } = req.body;
//console.log("req.body: ", req.body);
if (firstName === "" || lastName === "" || signature === "") {
res.render("petitionerror", {
error: "Please fill out all the elements before submitting",
});
} else {
addSignature(firstName, lastName, signature).then((data) => {
res.cookie("petition_signed", "yes");
console.log(data);
});
res.redirect("/thanks");
}
});
app.get("/thanks", (req, res) => {
res.render("thankyou", {
layout: "main",
});
});
app.get("/signers", (req, res) => {
getSignatures().then((data) => {
res.render("signers", { success: true, rows: data.rows });
});
});
app.listen(8080, () => console.log("listening on 8080"));
解决方案
你有它的结构方式,它试图在res.cookie
之后做,res.redirect
因为 addSignature 是一个异步函数。
addSignature(firstName, lastName, signature).then((data) => {
res.cookie("petition_signed", "yes");
console.log(data);
res.redirect("/thanks");
});
您需要确保res.cookie
在之前调用redirect
(它将标头返回给客户端)
推荐阅读
- swift - 如何选择 algolia 搜索命中并将其重定向到所需的 Viewcontroller?
- sql - 如何在 DolphinDB 查询中从分布式表中消除重复记录
- javascript - 在某些站点上,MouseEvent 对象的 x 和 y 值与 Debugger API 调度的 x 和 y 值不同
- java - 有没有办法让 System.out.print 在循环中打印一次不同的东西?
- c++ - 有没有办法用父类命名空间/类空间来引用子类?
- node.js - Firestore 函数 listCollections() 仅返回空数组
- javascript - 如何删除 Quill.js 工具栏边框?
- html - 如何将 A3 html 文档分成两个 A4
- java - 如果对象类型来自已编译的 .class 文件,如何避免在 Set 中存储重复项?
- kotlin - 如何处理泛型类中的可为空类型