res.send() vs res.json()

halloyun·2023년 12월 7일
post-thumbnail

res.json()으로 객체를 보낼때

app.get("/", function (req, res) {
    res.json({ say: "안녕" });
});

Content-Type이 json인것을 확인할 수 있다.

res.send()로 보낼때

app.get("/", function (req, res) {
    res.send("안녕");
});

app.get("/", function (req, res) {
    res.send({ say: "안녕하세요" });
});

Content-Type가 들어오는 파라미터에 따라서 달라지는걸 확인할 수 있다.

요약

  • res.send()는 send에 전해진 argument에 따라서 Content-type이 자동적으로 만들어진다. 이게 기본이다.
  • res.json()은 json이 아닌 것도 json 형식으로 바꾸어서 보내준다. 즉 content-type 헤더를 application/JSON으로 고정한다.

결론

둘은 별 다른 차이점이 없다.






참고


https://yohanpro.com/posts/nodejs/express-response

profile
안뇽! 자기소개는 밝게

0개의 댓글