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

Jaewoo Gwak·2021년 11월 9일
0

에러처리

목록 보기
1/2
post-thumbnail

NodeJS로 서버 개발을 할 때 이런 에러를 마주했다.

구글링 끝에 res.json 응답이 두 번 이상 처리될 때 발생하는 에러라고 짐작할 수 있었다.

내가 개발하던 코드를 예시로,

if (user.email === req.body.email) {
  if (user.password === req.body.password) {
    console.log(res.json(database.users[0]))
    return res.json("success") 
   }
}

이런 코드에서 console.log(res.json(database.users[0]))return res.json("success") 이 부분에서 두 번의 호출이 발생한다.

특히 res.json(database.users[0])부분은 console.log 안에 작성 되었음에도 res.json 호출을 한다.

그래서 console.log 코드를 삭제해버렸다.

다행히 잘 된다.

핵심은 res.json 코드가 중복되면 안된다는거랄까?

profile
꾸준하게 나아가고 싶다

0개의 댓글