2013-09-27 39 views
154

res.sendres.json之間的實際區別是什麼,因爲兩者似乎都執行相同的響應客戶端操作。Express.js中res.send和res.json之間的區別

+58

花點時間注意人們如何發佈答案只是去github並閱讀源代碼。這是一個學習和建立的好習慣。真相在於源頭。 –

+7

@PeterLyons使用源,盧克! – wprl

+24

@PeterLyons我同意這是一個好習慣,但是你的意思是說內存應該看看源代碼而不是問這個問題?這不是打敗了這個網站的目的嗎?這個問題的出現,以及提到一個好源(The Source!)的答案是有用的。 – LinusR

回答

168

傳遞對象或數組時,這些方法是相同的,但res.json()也將轉換非有效JSON的非對象,如nullundefined

該方法還使用json replacerjson 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); 
6

查看標題發送...
res.send使用內容類型:text/html
res.json使用內容類型:應用程序/ json