本文大约 1000 字。
在系统原型设计阶段,或后端接口不足备的情况下,如何验证模型信息的完整性?此时 mock 是一个不错的选择。
一般开发者可能倾向于直接写后端接口,哪怕只是返回假数据。之前作者也是这么想的,后来在试用了 mock 工具之后,想法转变了。
首先,全局安装 json-server:
yarn global add json-server
然后在 /go 目录下创建一个 db.json 文件,内容如下:
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" },
{ "id": 2, "title": "json-server2", "author": "typicode2" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
接着在 /go 目录下以如下命令启动 json-server:
json-server -p 8080 --watch db.json
这里的 8080 端口,是为了与之前使用过的端口保持一致。
在前端 vue 组件里,这样调用:
axios.get('/api/posts/1')
.then(function (response) {
console.log("result",response);
})
运行项目,就可以在控制台看到打印的结果。
直接访问接口地址也可以,例如:http://localhost:3000/posts,或http://localhost:3000/posts/1。
json-server 的妙处在于,它允许使用一个 json 文件定义数据,并且修改 json 内容,json-server 不需要重启,接口内容自动更有变化;更方便的地方还在于,像 /posts、/posts/1 这样的 Restful API 接口不需要手工定义,json-server 会根据 db.json 的内容自动按约定构建接口列表。
在 db.json 有模型 posts,所以以下接口都存在:
GET /posts
GET /posts/1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1
还支持参数过滤:
GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
GET /comments?author.name=typicode
还有分页:
GET /posts?_page=7
GET /posts?_page=7&_limit=20
排序:
GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc
等等。更多内容在这里查看:
https://github.com/typicode/json-server
源码
https://git.code.tencent.com/shiqiaomarong/vue-go-rapiddev-example/tags/v20191231
参考链接
https://yarnpkg.com/zh-Hans/docs/cli/global
https://github.com/typicode/json-server
[专栏]基于 vue+go 如何快速进行业务迭代?