[nodeJS] ERR_HTTP_HEADERS_SENT

쥬롬의 코드착즙기·2022년 12월 26일
0

code: ERR_HTTP_HEADERS_SENT

에러 원인은 역시 에러메시지에 있다.

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

원인

send를 두 번 이상 할 때 나는 에러!

클라이언트에게 send를 하고 난 뒤에 또 header를 설정하려고 할 때 나는 에러이다.
res.send() 메소드는 body를 인자로 받는다.
body에는 buffer, string, object, array를 넣을 수 있다.
res.send는 여기서 body type에 맞게 헤더에 Content-Type를 자동으로 설정해준다.

send를 하고 또 header를 설정한다는 건, send가 두 번 이상 나타날때 두 번째 send에서 header를 설정하는 작업이 있을 때 발생한다.

send => body타입 보고 header 설정 => header와 body 전송
=> 한번더 send => body타입 보고 header 설정...?!(여기서 에러)

해결방법

반복문 안에 res.send()가 중복되지 않는지 확인
내가 두 번 이상 쓴 게 아니라면 반복문에서 두 번 이상 들어간 것이다.
예시를 살펴보자.


app.post('/', (req, res)=>{
  const array=[1,2,3,4,5];
  array.map((item)=>{
    if (item>=4) res.send(item);    
  })
}
)

item>=4라는 조건에 4,5라는 두 item이 포함된다.
그래서 4를 send하고 나서 또 5를 send하려고 할 때 에러가 난다.

만약 4만 보내고 싶다면 반복이 종료될 수 있도록 return을 추가한다.


app.post('/', (req, res)=>{
  const array=[1,2,3,4,5];
  array.map((item)=>{
    if (item>=4) return res.send(item);    
  })
}
)

만약 4, 5를 모두 보내고 싶다면 새로운 array를 만들어 보낸다.


app.post('/', (req, res)=>{
  const array=[1,2,3,4,5];
  let newarray = [];
  array.map((item)=>{
    if (item>=4) newarray.push(item);   
  })
  res.send(newarray);
}
)
profile
코드를 짭니다...

0개의 댓글