it-source

Express.js의 res.send와 res.json의 차이

criticalcode 2022. 12. 19. 21:21
반응형

Express.js의 res.send와 res.json의 차이

의 실제 차이는 무엇입니까?res.send그리고.res.json양쪽이 클라이언트에 응답하는 같은 조작을 실행하는 것처럼 보이기 때문입니다.

오브젝트 또는 어레이가 전달될 때 방법은 동일합니다만,res.json()또, 다음과 같이 비표준 변환도 실시합니다.null그리고.undefined유효한 JSON이 아닙니다.

이 메서드에서는json replacer그리고.json spacesJSON을 더 많은 옵션으로 포맷할 수 있습니다.이러한 옵션은 다음과 같이 설정됩니다.

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()그 방법res.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()최종적으로는,

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

return this.send(body);

expressj의 소스 코드를 참조하십시오.

res.json최종적으로 콜하다res.send그 전에:

  • 을 존중하다json spaces그리고.json replacer앱 설정
  • 응답에 필요한 정보를 얻을 수 있습니다.utf-8문자 집합 및application/json콘텐츠 타입

보낸 헤더를 찾는 중...

res.send사용하다content-type:text/html

res.json사용하다content-type:application/json

edit: send는 실제로 주어진 내용에 따라 전송되는 내용을 변경하기 때문에 문자열은 다음과 같이 전송됩니다.text/html단, 만약 당신이 그것을 건네준다면, 그것은 그것을 방출한다.application/json.

res.json인수를 강제로 JSON으로 설정합니다.res.send는 비json 객체 또는 비json 어레이를 가져와서 다른 유형을 전송합니다.예를 들어:

그러면 JSON 번호가 반환됩니다.

res.json(100)

상태 코드가 반환되고 사용하라는 경고가 발생합니다.sendStatus.

res.send(100)

인수가 JSON 개체 또는 배열이 아닌 경우(null,undefined,boolean,stringJSON 로서 송신되는 것을 확인하려면 , 를 사용합니다.res.json.

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

반응형