【问题标题】:error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client错误:错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
【发布时间】:2020-09-22 02:14:33
【问题描述】:

我是 node.js 的新手,我正在使用常规 js 在客户端工作,但出现此错误:

错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头

我的服务器代码是:

app.get('/connect', function (req, res) {
    console.log("connect to the user");
    res.sendFile(path.join(__dirname, 'client', 'connect.html'));
});

app.post('/connect', function (req, res) {
    const userNameEnter = req.body.userName;
    const passwordEnter = req.body.password;

// //entering if the user and pass are correct
if (userNameEnter !== undefined && passwordEnter !== undefined) {
    User.findOne({ userName: userNameEnter }, function (err, user) {
        console.log(err);
        if (user !== null) { //can enter
            if (user.userPassword === passwordEnter) {
                res.json({
                    status: "seccess",
                    user: "canEnter"
                });
                console.log("can enter");
                res.redirect("/gameManage/" + user.id);
            } else {//cant enter
                res.json({
                    status: "seccess",
                    user: "notOk"
                });
            }
        } else {//cant enter
            res.json({
                status: "seccess",
                user: "notOk"
            });
            console.log("cant enter");
        }
    });
}
console.log(newUser);

});

我必须发送 JSON,因为 js 需要知道下一步该做什么。 如何以另一种方式重定向它,以便在 URL 行中有 userId 的参数?

【问题讨论】:

  • 你在res.json之后做res.redirect,因此出现错误
  • @warl0ck 我知道,但我必须同时做这两件事,所以我可以修复它吗?
  • 不能。您不能发送 JSON 响应重定向响应。这是一个或另一个。
  • @deceze 但是如果我需要同时做这两个...有没有其他方法可以做到这一点?
  • 您可能只想在 JSON 响应中发送一个 URL,客户端将通过 Javascript 访问该 URL。您不想重定向 HTTP 响应。

标签: javascript node.js


【解决方案1】:

您不能向客户端发送响应,然后也重定向客户端。您应该将重定向路径发送到客户端,然后使用 javascript 从客户端重定向

res.json({
     status: "seccess",
     user: "canEnter",
     redirectPath: "/gameManage/" + user.id
});

在客户端

if (response.redirectPath) {
    window.location.href = response.redirectPath;
}

【讨论】:

    猜你喜欢
    • 2020-05-26
    • 2018-09-19
    • 2023-01-19
    • 2021-02-26
    • 2021-08-20
    • 2019-09-28
    • 2019-12-25
    • 2021-11-30
    相关资源
    最近更新 更多