# 響應
響應對象可以向客戶端發送響應,并終止請求。若沒有從路由處理函數調用這些方法,則客戶端請求將保持掛起狀態。其有以下這些方法:
* res.status() Set status code.
* res.type() Set MIME type.
* **res.send()** Send a response of various types.
* **res.json()** Send a JSON response.
* **res.render()** Render a view template.
* res.sendStatus() Set the response status code and send its string representation as the response body.
* res.sendFile() Send a file as an octet stream.
* res.end() End the response process.
* res.redirect() Redirect a request.
* res.download() Prompt a file to be downloaded.
* res.jsonp() Send a JSON response with JSONP support.
```
// 響應 JSON 格式數據
const express = require('express');
const app = express();
app.get('/', (req, res) => {
let jsonData = {name : 'xx', age : 11};
// 把上面的 JS 對象自動轉 JSON , 并設置響應頭Content-Type的值為application/json;chasert=utf-8
res.json(jsonData);
});
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!');
});
```
- NodeJs
- 01-萬維網
- 02-CS 架構 VS BS 架構
- 03-Web 服務器訪問流程
- 04-url
- 05-網絡傳輸協議
- 06-HTTP 協議
- 07-報文
- 08-命令行界面
- 09-什么是 Node.js
- 10-環境安裝及配置
- 11-JavaScript 代碼運行環境
- 12-全局對象
- 13-Buffer
- 14-模塊化
- 15-EventEmitter
- 16-path模塊
- 17-流式操作
- 18-包
- 19-模板技術
- 20-ejs入門
- 21-express
- 01-什么是express
- 02-Hellow Express
- 03-靜態資源服務
- 04-路由
- 05-模塊化路由處理程序
- 06-中間件
- 07-手動實現中間件
- 08-常用內置中間件和第三方中間件
- 09-響應
- 10-獲取請求參數
- 11-Express 中使用模板引擎
- 22-web存儲與安全
- 01-cookie
- 02-sessionStorage
- 03-localStorage
- 04-base64
- 05-https
- 06-同源策略