首页 > 解决方案 > 在 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"));

标签: javascriptnode.jsexpress

解决方案


你有它的结构方式,它试图在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(它将标头返回给客户端)


推荐阅读