[Node] Express의 res.send() 와 res.json()

jiseong·2021년 12월 4일
0

T I Learned

목록 보기
147/291

사용자의 HTTP 요청에 대해 응답을 해줄 때, res.send()와 res.json()를 이용하게 되는데 어떤 차이가 있는지 궁금했다.

app.get('/test', (req, res) => {
   // do something...
})

res.send()

res.send()메서드를 사용하면 따로 Content-Type를 지정해주지 않아도 인자로 어떤 데이터 타입을 보내는지에 따라서 메서드 내부에서 알아서 Content-Type을 지정 해준다.

e.g. Buffer, String, an Object and an Array
//    res.send(Buffer.from('wahoo'));
//    res.send({ some: 'json' });
//    res.send('<p>some html</p>');

string 타입을 예시로 본다면 실제 express 라이브러리의 내부 코드에서 Content-Type을 지정해준다.

res.send = function send(body) {
  var chunk = body;
  var encoding;
  var req = this.req;
  var type;

  // 생략...
  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;
  }
  
  if (typeof chunk === 'string') {
      encoding = 'utf8';
      type = this.get('Content-Type');

      // reflect this in content-type
      if (typeof type === 'string') {
        this.set('Content-Type', setCharset(type, 'utf-8'));
      }
   }
	
  return this;
};

res.json()

express 라이브러리의 내부 코드를 보면 res.json() 메서드도 결국 마지막에 res.send()를 부른다.
그렇기 때문에 json 형식으로 데이터를 보낸다면 의도가 드러나는 json()메서드를 사용하는 것이 좋지않을까 생각된다.
( 추가적으로 공백같은 옵션을 지정해줄수도 있는 것 같다.)

res.json = function json(obj) {
  var val = obj;

  // allow status / body
  if (arguments.length === 2) {
    // res.json(body, status) backwards compat
    if (typeof arguments[1] === 'number') {
      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');
      this.statusCode = arguments[1];
    } else {
      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');
      this.statusCode = arguments[0];
      val = arguments[1];
    }
  }

  // settings
  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)

  // content-type
  if (!this.get('Content-Type')) {
    this.set('Content-Type', 'application/json');
  }

  return this.send(body);
};

Reference

0개의 댓글