res.send vs res.json

CH_Hwang·2022년 2월 18일
0

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;
    }
    ...
  }

object일때 this.json을 호출함 (여기서 chunk = body)

res.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);
};

이경우 마지막에 this.send를 통해 보냄

  • object 형식일 때

    res.send

    • res.send
    • res.json
    • res.send

    res.json

    • res.json
    • res.send

    결론: res.json이 한번이라도 함수 호출이 적음. object 형식(json)으로 보낼때는 Res.json을 쓰자.

0개의 댓글