[TIL] #51 response json, send

ddalkigum·2021년 5월 30일
1
post-thumbnail

한주에 하나씩 쓰는 걸 목표로 글을 써보자

생각도 정리하고, 이번주에 뭐했는지? 이건 개인 노션에 정리하고,
WIL로 써야하나 TIL로 써야하나 고민했는데, WIL은...
그냥 기존에 쓰던대로 이어가고 싶다

WIL은 1부터 다시 해야되서 쓴게 없어 보일 거 같다


response

response를 보내면서 궁금하던게 있었다
response.send와 response.json 두개의 차이가 뭘까

send를 보내도, json을 보내도 응답은 똑같은데 왜 나눴을까

그래서 express의 코드를 들어가보고 살펴봤다 어떤 구조로 되어있을까

response.json을 보게 되면 object를 인자로 받아온다

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

  // 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);
};

결과적으로는 send로 보내게 되어, 처리를 한다
그렇다면 response.json으로 보내는 것 보다 send로 보내는게 효율적일까??

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

  // settings
  var app = this.app;

  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 json 
        return this.json(chunk);
      }
      break;
  }

  // write strings in utf-8
  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'));
    }
  }

  // determine if ETag should be generated
  var etagFn = app.get('etag fn')
  var generateETag = !this.get('ETag') && typeof etagFn === 'function'

  return this;
};

send에서 응답을 처리한다, 여기서 주의할 곳은 swtich 구문에서 object를 받을 경우
json함수를 호출 한다는 것인데, 대략적인 흐름은 이렇다

response.json

  • json메서드를 호출
  • json은 받은 object를 stringify하여, send를 호출

response.json

  • send메서드를 호출 (object)
  • json으로 object를 넘겨줌
  • json은 받은 object를 stringify하여, send를 호출

이렇게 보면 send를 호출하는 것 보다 json을 호출하는게 낫지 않을까 싶다
결과적으로 send로 향하기는 하지만, object를 넘기게 되면 json을 호출하고, send를 호출하게 된다.

눈으로 보기에도 그렇고, 호출하는 횟수를 생각한다면 response.json으로 무엇을 보내는지
확실하게 보여주는게 좋지 않을까 싶다

Express response code

profile
딸기검 -본캐🐒 , 김준형 - 현실 본캐 🐒

0개의 댓글