Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

이건준·2022년 12월 8일
0

문제제기

  • Node에 MySql을 이용하여 posting 라우터에 댓글을 달 수 있는 API를 설계도중에 위와 같은 오류를 발견
.post(isLoggedIn, async (req, res, next) => {
    // 특정 게시글에 comment들을 등록합니다
    const { content } = req.body;
    const posting_id = req.params.posting_id;
    const user_id = req.user.id;
    try {
      const comment = await Comment.create({
        user_id,
        posting_id,
        content,
      });
      res.json(comment);
      res.redirect("/");
    } catch (err) {
      console.error(err);
      next(err);
    }
  });
  • 위 코드는 오류가 발생한 부분의 코드이다

문제해결

  • 문제의 원인은 클라이언트에서 보낸 요청에 의해서 서버에서 보낼 response값이 하나 이상일 경우에 생기는 오류이다

  • 즉 위에서 res를 통해 comment데이터를 보내는 동시에 redirect까지 수행하려하니 오류가 발생한 것이다

.post(isLoggedIn, async (req, res, next) => {
    // 특정 게시글에 comment들을 등록합니다
    const { content } = req.body;
    const posting_id = req.params.posting_id;
    const user_id = req.user.id;
    try {
      const comment = await Comment.create({
        user_id,
        posting_id,
        content,
      });
      res.json(comment);
      //res.redirect("/");
    } catch (err) {
      console.error(err);
      next(err);
    }
  });
  • 나는 Comment에 대한 API설계에 따른 올바른 값을 전달받았다는 응답값만 전달해주면 되므로 redirect부분을 주석처리하여 오류를 해결하였다

0개의 댓글