下面我们快速实现一套RESTFUL的mock接口。
创建数据文件
新建文本文件,名为db.json
,内容如下:
{
"posts": [
{ "id": 1, "title": "json server入门", "author": "乙醇" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
运行mock server
在命令行中运行
json-server --watch db.json
验证
在浏览器中访问http://localhost:3000/posts/1
,这时候应该可以返回
{ "id": 1, "title": "json server入门", "author": "乙醇" }
路由
根据上面的data文件,默认情况下json-server会生成下面一些路由
复数路由
GET /posts
GET /posts/1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1
GET /comments
GET /comments/1
POST /comments
PUT /comments/1
PATCH /comments/1
DELETE /comments/1
单数路由
GET /profile
POST /profile
PUT /profile
PATCH /profile
潜规则
- POST, PUT, PATCH 或DELETE真的会对db.json文件产生影响,比如会保存新增的数据
- 请求body中需要传json字符串,比如
{"name": "Foobar"}
- POST, PUT 或 PATCH请求headers中必须包括
Content-Type: application/json