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

DongHun, Kim·2023년 4월 13일
0

문제 해결

목록 보기
1/3

😣 문제 상황

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

Next.js에서 API route로 요청을 보냈을 때 위와 같은 에러가 발생.

✅ 해결

해당 에러는 서버에서 둘 이상의 응답을 보낼 때 발생한다는 것을 확인.

if (findResult === null) {
  res.status(404).end();
}
res.status(200).json(findResult);

에러가 발생하는 API에서 중복으로 응답을 보낼 수 있는 부분을 찾아서 다음과 같이 Early return하도록 함.

if (findResult === null) {
  res.status(404).end();
  return;
}
res.status(200).json(findResult);

참고한 자료
https://velog.io/@soshin_dev/ERRHTTPHEADERSSENT-Cannot-set-headers-after-they-are-sent-to-the-client-오류

profile
프론트엔드 개발자가 될래요

0개의 댓글