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()
그 방법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
,string
JSON 로서 송신되는 것을 확인하려면 , 를 사용합니다.res.json
.
언급URL : https://stackoverflow.com/questions/19041837/difference-between-res-send-and-res-json-in-express-js
'it-source' 카테고리의 다른 글
CodeIgniter의 머리글 및 바닥글 (0) | 2022.12.19 |
---|---|
Express.js의 next()를 사용하여 다음 미들웨어에 변수 전달 (0) | 2022.12.19 |
PHP 함수 주석 (0) | 2022.12.19 |
아포스트로피로 시작하는 테이블을 삭제하는 방법 (0) | 2022.12.19 |
컴포넌트가 라이브러리를 강제로 재설치하도록 하는 방법 (0) | 2022.12.19 |