簡單來說就是 如果服務器端沒有數據返回到客戶端 那么就可以用 res.end, 但是 如果 服務器端有數據返回到客戶端 這個時候必須用res.send ,不能用 res.end(會報錯) 。
官方說明
- res.end() 終結響應處理流程。
- res.send() 發送各種類型的響應。
1)res.end([data] [,encoding])**
結束響應過程。這個方法實際上來自Node核心,特別是http.ServerResponse的response.end()方法。
用於在沒有任何數據的情況下快速結束響應。如果需要響應數據,請使用res.send()和res.json()等方法。
res.end();res.status(404).end();
2)res.send([body])**
發送HTTP響應。
所述body參數可以是一個Buffer對象,一個String,對象,或一個Array。例如:
res.send(new Buffer('whoop'));res.send({ some: 'json' });res.send('<p>some html</p>');res.status(404).send('Sorry, we cannot find that!');res.status(500).send({ error: 'something blew up' });
此方法為簡單的非流式響應執行許多有用的任務:例如,它自動分配Content-Length
HTTP響應頭字段(除非先前已定義)並自動提供HEAD和HTTP緩存支持。
當參數是Buffer對象時,該方法將Content-Type
響應頭字段設置為“application / octet-stream”,除非先前定義如下所示:
res.set('Content-Type', 'text/html');res.send(new Buffer('<p>some html</p>'));
當參數為String,該方法將設置Content-Type為
“text / html”:
res.send('<p>some html</p>');
當參數是Array或Object,Express以JSON表示響應:
res.send({ user: 'tobi' });res.send([1,2,3]);
總結
- 參數類型的區別:
- res.end() 參數為: a Buffer object / a String
- res.send() 參數為: a Buffer object / a String / an object / an Array
- 發送服務器內容不同
- res.end() 只接受服務器響應數據,如果是中文則會亂碼
- res.send() 發送給服務端時,會自動發送更多的響應報文頭,其中包括 Content-Tpye: text/html; charset=uft-8,所以中文不會亂碼