programing

Express.js에서 res.send와 res.json의 차이점

new-time 2020. 5. 14. 22:34
반응형

Express.js에서 res.send와 res.json의 차이점


사이의 실제 차이가 무엇

res.send

res.json

모두 클라이언트에 대한 응답의 동일한 작업을 수행하는 것 등입니다.


상기 방법은 오브젝트 또는 어레이가 전달 될 때와 동일하지만,

res.json()

또한 비 객체 변환 할

null

undefined

유효 JSON 아니다.이 방법은

json replacer

json spaces

응용 프로그램 설정 도 사용 하므로 더 많은 옵션으로 JSON 형식을 지정할 수 있습니다. 이러한 옵션은 다음과 같이 설정됩니다.

app.set('json spaces', 2);
app.set('json replacer', replacer);

그리고 다음

JSON.stringify()

과 같이 전달되었습니다 .

JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation

다음은

res.json()

send 메소드에없는 메소드 의 코드입니다 .

var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);

이 방법

res.send()

은 결국 a 로 끝납니다.

this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);

https://github.com/visionmedia/express/blob/ee228f7aea6448cf85cc052697f8d831dce785d5/lib/response.js#L174

res.json

결국을 호출

res.send

하지만 그 전에는

  • json spacesjson replacer앱 설정을 존중
  • 응답에 utf8 문자셋과 application / json 컨텐츠 유형이 있는지 확인하십시오.

보낸 헤더를 보면 ...

 

res.send는 content-type : text / html을

 

사용하고 res.json은 content-type : application / json을 사용합니다참고 URL :

https://stackoverflow.com/questions/19041837/difference-between-res-send-and-res-json-in-express-js

반응형