[TOC]
# 響應
響應對象可以向客戶端發送響應,并終止請求。若沒有從路由處理函數調用這些方法,則客戶端請求將保持掛起狀態。其有以下這些方法:
1. **res.status()** 設置狀態代碼( Set status code.)
2. **res.type()** 設定MIME類型(Set MIME type.)
3. **res.send()** 發送各種類型的響應(Send a response of various types.)
4. **res.json({data})** 自動設置響應頭(Send a JSON response.)
5. **res.render()** 渲染模板(Render a view template.)
6. **res.sendStatus()** 設置響應狀態代碼,并將其字符串表示形式作為響應體發送。
7. **res.sendFile()** 以八位字節流的形式發送文件。
8. **res.end()** 終結響應處理流程。
9. **res.redirect()** 重定向請求。(Redirect a request.)
10. **res.download()** 提示下載文件。
11. **res.jsonp()** 發送一個支持 JSONP 的 JSON 格式的響應。(Send a JSON response with JSONP support.)
響應 JSON 格式數據
```
// 響應 JSON 格式數據
const express = require('express');
const app = express();
app.get('/', (req, res) => {
let jsonData = {name : 'xx', age : 11};
res.json(jsonData);//將對象 jsonData 轉換為 json 格式
});
app.listen(8888, () => {
console.log('Example app listening on port 8888!');
});
```
文件下載
```
// 文件位置 myapp/a.txt
const path = require('path');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.download(path.join(__dirname, 'a.txt'));//被下載文件存放路徑
});
app.listen(8888, () => {
console.log('Example app listening on port 8888!');
});
```