<aside> 💡 shortly_mvc 스프린트에서 express를 잘 사용하지 못해 많은 시행착오를 겪었다. 이에 대해 제대로 한번 정리를 해보고자 한다.

</aside>

** 주의사항 return res.sendStatus(404)를 하게 된다면, 상태코드와 메세지를 설정하고 해당 함수는 모두 종료되겠지만, 그냥, res.sendStatus(200)과 같이 return 없이 작성하게 되면, 해당 상태와 메세지를 보내고 그 밑에 있는 함수들이 실행되게 된다. 즉, 그냥 일반 함수와 똑같이 생각하자!

send([body]) 메소드

이 메소드는 HTTP Response를 보내는데 사용이 된다. 여기에서 body parameter은 Object, Array, String과 같은 다양한 형태로 보낼 수 있다. 단, String일 경우, this method will set the Content-Type to “text/html” 만약, Array or Object일 경우, Express responds with the JSON representation.

실사용 예시는 아래와 같다. (출처: http://expressjs.com/ko/api.html#res.send)

res.send({ some: 'json' })
res.send('<p>some html</p>')
res.status(404).send('Sorry, we cannot find that!')
res.status(500).send({ error: 'something blew up' })

sendStatus() 메소드

이 메소드는 response HTTP code를 정하고, 해당 코드의 respresentation을 body에 담아 보내게 된다. ❗️이 메소드 자체가 바디를 생성하고 보내기 때문에, ❗️추가적으로 sendStatus(200).json(sth) 이나 sendStatus(200).send(sth)은 유효하지 않은 방식이다. ❗️내가 자주 잘못썼던 방식이다 꼭 사용방법을 숙지하고 사용하자.

실사용 예시는 아래와 같다.

res.sendStatus(200) // equivalent to res.status(200).send('OK')
res.sendStatus(403) // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404) // equivalent to res.status(404).send('Not Found')
res.sendStatus(500) // equivalent to res.status(500).send('Internal Server Error')

res.redirect([status,] path) 메소드

이 메소드는 path에서 derived된 url로 redirect하는 메소드이다. status를 명시하지 않고, 단순히 res.redirect(path)형식으로도 사용가능하며, 이 경우 status는 default 값으로 "302 Found"가 되게 된다. ❗️이 메소드 역시 사용방법을 제대로 모르고 마음대로 쓰다가 큰 코 다친 메소드이다. ❗️원래는 res.status(302).redirect(url)과 같이 썼지만, 작동하지 않는다! 주의하자!

실사용 예시는 아래와 같다.

res.redirect('/foo/bar')
res.redirect('<http://example.com>')
res.redirect(301, '<http://example.com>')
res.redirect('../login')