res.send
和res.json
之間的實際區別是什麼,因爲兩者似乎都執行相同的響應客戶端操作。Express.js中res.send和res.json之間的區別
154
A
回答
168
傳遞對象或數組時,這些方法是相同的,但res.json()
也將轉換非有效JSON的非對象,如null
和undefined
。
該方法還使用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()
方法的代碼,發送方法沒有:
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);
50
res.json
最後調用res.send
,但它之前:
- 方面的
json spaces
和json replacer
應用程序設置 - 確保響應將有UTF8字符集和應用程序/ JSON內容類型
6
查看標題發送...
res.send使用內容類型:text/html
res.json使用內容類型:應用程序/ json
相關問題
- 1. express.js中app.use和app.get之間的區別
- 2. NodeJS REST API和res.json/res.send
- 3. 將res.send和res.json結合使用
- 4. Express.js中間件res.send,每個res.send通話功能()
- 5. 之間的〜/和的區別../
- 6. res.send()express.js自動重定向
- 7. '#','%'和'$'之間的區別
- 8. {!!之間的區別!!}和{{}}
- 9. '+ ='和'= +'之間的區別?
- 10. 「。+」和「。+?」之間的區別
- 11. .eq之間的區別。和==
- 12. #。/和#之間的區別。 ./
- 13. !=和!之間的區別==
- 14. 「%〜dp0」和「。\」之間的區別?
- 15. | =和^ = css之間的區別
- 16. 之間的區別。和#
- 17. ==和case之間的區別?
- 18. 「**/* /」和「** /」之間的區別?
- 19. jQuery - '。'之間的區別和「#」
- 20. 「?1」和「?」之間的區別
- 21. `%in%`和`==`之間的區別
- 22. fmod和%之間的區別
- 23. 之間的區別:+和:+
- 24. make中的「$(shell ...)」和「$$(...)」之間的區別
- 25. python中的[]和[,,]之間的區別
- 26. javascript中的/ * * /和//之間的區別
- 27. $之間的區別?和PowerShell中的$ LastExitCode
- 28. jQuery中的$和$()之間的區別
- 29. C中的/ +和+之間的區別?
- 30. 類區域和堆之間的區別
花點時間注意人們如何發佈答案只是去github並閱讀源代碼。這是一個學習和建立的好習慣。真相在於源頭。 –
@PeterLyons使用源,盧克! – wprl
@PeterLyons我同意這是一個好習慣,但是你的意思是說內存應該看看源代碼而不是問這個問題?這不是打敗了這個網站的目的嗎?這個問題的出現,以及提到一個好源(The Source!)的答案是有用的。 – LinusR