🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 响应 响应对象可以向客户端发送响应,并终止请求。若没有从路由处理函数调用这些方法,则客户端请求将保持挂起状态。其有以下这些方法: * 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!'); }); ```