에러
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:393:5)
at ServerResponse.setHeader (node:_http_outgoing:644:11)
at ServerResponse.header (/home/cloudcoke/my/nodejs/practice/221215/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/home/cloudcoke/my/nodejs/practice/221215/node_modules/express/lib/response.js:174:12)
at done (/home/cloudcoke/my/nodejs/practice/221215/node_modules/express/lib/response.js:1035:10)
at /home/cloudcoke/my/nodejs/practice/221215/node_modules/nunjucks/src/environment.js:41:5
at RawTask.call (/home/cloudcoke/my/nodejs/practice/221215/node_modules/asap/asap.js:40:19)
at flush (/home/cloudcoke/my/nodejs/practice/221215/node_modules/asap/raw.js:50:29)
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
code: 'ERR_HTTP_HEADERS_SENT'
}
에러 원인
- 이미 응답을 보냈는데 다시 또 응답을 보내려고 해서 에러가 발생했다.
문제 코드
app.get("/", (req, res) => {
const user = app.get("login");
console.log(user);
if (user !== undefined) {
const nickname = user["nickname"];
res.render("index", { nickname: `${nickname}님 안녕하세요` });
}
res.render("index");
});
app.post("/login", (req, res) => {
const { id, pw } = req.body;
if (isIdPwCorrect(id, pw)) {
res.redirect("/");
}
res.render("login");
});
해결
- if ... else 문으로 true일 경우와 false일 경우에 할 동작을 명확히 해주었다.
app.get("/", (req, res) => {
const user = app.get("login");
if (user !== undefined) {
const nickname = user["nickname"];
res.render("index", { nickname: `${nickname}님 안녕하세요` });
} else {
res.render("index");
}
});
app.post("/login", (req, res) => {
const { id, pw } = req.body;
if (isIdPwCorrect(id, pw)) {
res.redirect("/");
} else {
res.render("login");
}
});
참고