Express를 이용해서 REST API 서버를 개발하고 있다. 지금 작성된 서버 API의 경우 res.json
응답을 하는 경우(직접 개발) 과 res.send
로 응답(express 기본) 하는 경우로 나뉘어져있어서 궁금해서 찾아봤고, 정리해놓기로 마음 먹엇다.
먼저 res.json
소스코드의 일부는 아래와 같다.
res.json = function json(obj) {
var val = obj;
// 생략...
var app = this.app;
var escape = app.get('json escape')
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = stringify(val, replacer, spaces, escape)
if (!this.get('Content-Type')) {
this.set('Content-Type', 'application/json');
}
return this.send(body);
};
여기서 핵심 포인트는 아래와 같다.
application/json
으로 변경한다res.send
의 소스코드의 일부는 아래와 같다.
res.send = function send(body) {
var chunk = body;
// 생략....
switch (typeof chunk) {
// string defaulting to html
case 'string':
if (!this.get('Content-Type')) {
this.type('html');
}
break;
case 'boolean':
case 'number':
case 'object':
if (chunk === null) {
chunk = '';
} else if (Buffer.isBuffer(chunk)) {
if (!this.get('Content-Type')) {
this.type('bin');
}
} else {
return this.json(chunk);
}
break;
}
// 생략..
return this;
}
이번에도 핵심 포인트는 아래와 같다.
res.json
을 실행두 가지 함수의 실행 호출 순서는 다음과 같다.
1. res.send
2. res.json
따라서 어차피 json으로 결과를 클라이언트에 전송해야 한다면 res.json
이 적절할지도 모르겠다.
협업하는 입장에서도 훨씬 직관적으로 이해할 수 있을 것 같다. 혹시나 모르니 오픈소스나 개발 블로그들을 찾아보면서 여러 사례들을 탐구해보는 것도 좋은 공부가 될 것 같다.