需要用node写api,狗哥说express比较合适。
come on.
hello world
1  | npm install -g express //安装 express  | 
npm list express 查看版本
导入
1  | var express = require('express'); // 导入 express  | 
路由映射
1  | var router = express.Router(); // 接上文  | 
端口
1  | var port = process.env.PORT || 8080; // 服务端口  | 
启动
1  | node app1.js  | 
进阶
访问路径
1  | // :name 获取路径的参数  | 
更多请求方式
1  | var bodyParser = require('body-parser');  | 
body-parser模块的作用,是对POST、PUT、DELETE等 HTTP 方法的数据体进行解析。app.use用来将这个模块加载到当前应用。有了这两句,就可以处理POST、PUT、DELETE等请求了。
1  | // post 映射  | 
中间件
1  | // 定义方式 next 下一个中间件  | 
REST API
REST API 的基本用法
(1) 命令行进入demos/rest-api-demo目录,执行下面的命令。
1  | $ npm install -S json-server  | 
(2) 在项目根目录下,新建一个 JSON 文件db.json。
1  | {  | 
(3) 打开package.json,在scripts字段添加一行。
1  | "scripts": {  | 
(4) 命令行下执行下面的命令,启动服务。
1  | $ npm run server  | 
(5)打开 Chrome 浏览器的 Postman 应用。依次向http://127.0.0.1:3000/posts、http://127.0.0.1:3000/posts/1发出GET请求,查看结果。
(6)向http://127.0.0.1:3000/comments发出POST请求。注意,数据体Body要选择x-www-form-urlencoded编码,然后依次添加下面两个字段。
1  | body: "hello world"  | 
发出该请求后,再向http://127.0.0.1:3000/comments发出GET请求,查看结果。
(7) 向http://127.0.0.1:3000/comments/2发出PUT请求,数据体Body要选择x-www-form-urlencoded编码,然后添加下面的字段。
1  | body: "hello react"  | 
发出该请求后,再向http://127.0.0.1:3000/comments发出GET请求,查看结果。
(8)向http://127.0.0.1:3000/comments/2发出delete请求。
发出该请求后,再向http://127.0.0.1:3000/comments发出GET请求,查看结果。