【发布时间】: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