- 内容简介
- 译者序
- 前言
- 第 1 章 安装配置新项目
- 第 2 章 Flexbox 布局介绍
- 第 3 章 用 React Native 开发一个应用
- 第 4 章 在 React Native 中使用导航
- 第 5 章 动画和滑动菜单
- 第 6 章 用 React Native 绘制 Canvas
- 第 7 章 使用 React Native 播放音频
- 第 8 章 你的第一个自定义视图
- 第 9 章 Flux 介绍
- 第 10 章 处理复杂的应用程序状态
- 第 11 章 使用 Node 来实现服务端 API
- 第 12 章 在 React Native 中使用文件上传
- 第 13 章 理解 JavaScript Promise
- 第 14 章 fetch 简介
- 第 15 章 在 iOS 中使用 SQLite
- 第 16 章 集成 Google Admob
- 第 17 章 React Native 组件国际化
- 附录 A React.js 快速介绍
- 附录 B Objective-C Primer
- 附录 C webpack 入门
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
Request 和 Response 对象
- Express 的 Request 和 Response 对象继承自 Node HTTP 的 Request 和 Response 对象:
// https://github.com/strongloop/express/lib/request.js 文件 var req = exports = module.exports = { __proto__: http.IncomingMessage.prototype } // https://github.com/strongloop/express/lib/response.js 文件 var res = module.exports = { __proto__: http.ServerResponse.prototype }
- 使用 Node 的 HTTP 方法
我们可以直接在 Express 中使用 Node 的 write 和 end 方法:
var express = require('express'); var app = express(); app.get('/', function(request, response){ response.write('Hello World'); response.end(); }); app.listen(3000);
等同于这段代码:
var express = require('express'); var app = express(); app.get('/', function(request, response){ response.send('Hello World'); }); app.listen(3000);
- 返回 JSON 数据
send 函数可以将对象和数据转换为 JSON 格式返回:
app.get('/todos', function(request, response) {
var todos = ["Todo item 1", "Todo item 2", "Todo item 2"]; response.send(todos); });
在 curl 命令中添加-i 参数:
curl -i http://localhost:3000/todos
我们看到如下的返回信息:
HTTP/1.1 200 OK X-Powered-By: Express Content-Type: application/json; charset=utf-8 ["Todo item 1", "Todo item 2", "Todo item 2"]
- 返回 HTML 信息
send 函数可以识别 HTML 字符串并设置对应的响应头:
app.get('/blocks', function(request, response) { var blocks = '<ul><li>Todo item 1</li><li>Todo item 2</li></ul>'; response.send(blocks); });
使用 curl 来测试:curl -i http://localhost:3000/blocks。
HTTP/1.1 200 OK X-Powered-By: Express Content-Type: text/html; charset=utf-8 <ul><li>Todo item 1</li><li>Todo item 2</li></ul>
- 使用 redirect 设置合适的响应头来重定向到新的地址
app.get('/todos', function(request, response) { response.redirect('/parts'); });
使用 curl 来测试:curl -i http://localhost:3000/todos。
HTTP/1.1 302 Moved Temporarily X-Powered-By: Express Location: /parts Content-Type: text/plain; charset=utf-8 ! Moved Temporarily. Redirecting to /parts
- 自定义重定向的状态码
函数的第一个参数会被解析为用于重定向的状态码:
app.get('/todos', function(request, response) { response.redirect(301, '/parts'); });
使用 curl 来测试:curl -i http://localhost:3000/todos。
HTTP/1.1 301 Moved Permanently X-Powered-By: Express Location: /parts Content-Type: text/plain; charset=utf-8 ! Moved Permanently. Redirecting to /parts
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论