前端虚拟接口---mock的用法
这几天在写自己的博客。。。然后后台接口什么的没来得及写。。。然后就想了下用mock去虚拟一个接口。json-serverJSON Server 是一个创建伪RESTful服务器的工具,具体使用方法可以看官方文档,这里直接讲在vue-cli 中的用法。
·
这几天在写自己的博客。。。然后后台接口什么的没来得及写。。。然后就想了下用mock去虚拟一个接口。
json-server
JSON Server 是一个创建伪RESTful服务器的工具,具体使用方法可以看官方文档,这里直接讲在vue-cli 中的用法。
配置流程
全局安装 $ npm install -g json-server
项目目录下创建 mock 文件夹
mock 文件夹下添加 db.json 文件,内容如下
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
- package.json 添加命令
"mock": "json-server --watch mock/db.json"
启动mock服务
- 命令行 $ npm run mock
命令行结果如图:
- 浏览器输入localhost:3000
- 浏览器输入localhost:3000/posts
db.json 进阶版 db.js
- 新建db.js
module.exports = function() {
var tree = require('./tree.json');
return {
tree
}
}
- 新建tree.json (这个文件为模拟接口数据)
{
"mate" : {
"columns" : [
{
"label":"排序",
"name" :"sort",
"span":12
}
],
"rows": [
{
"id" : 1,
"label": "一级 1",
"sort" : 1,
"children": [{
"id" : 11,
"label": "二级 1-1",
"sort" : 1,
"status":1
}],
"status":1,
"num" : false
},
{
"id" : 2,
"label": "一级 2",
"sort" : 2,
"children": [{
"id" : 21,
"label": "二级 2-1",
"sort" : 1,
"status":1,
"num" : true
}, {
"id" : 22,
"label": "二级 2-2",
"sort" : 2,
"status":0,
"num" : true
}],
"status":1,
"num" : true
},
{
"id" : 3,
"label": "一级 3",
"sort" : 3,
"children": [{
"id" : 31,
"label": "二级 3-1",
"sort" : 1,
"status":0,
"num" : false
}, {
"id" : 32,
"label": "二级 3-2",
"sort" : 2,
"status":1,
"num" : true
}],
"status":1,
"num" : true
}
],
"btns" :[
{
"action" : "add",
"url" : "/form.txt",
"label" : "增加顶级栏目",
"type" : "success",
"isApi" : false,
"useId" : -1,
"isSelector" : false
}
],
"actions":[
{
"action" :"add",
"url" : "/form.txt",
"label" : "增加",
"type" : "success",
"isApi" : false,
"useid" : 0
},
{
"action" :"edit",
"url" : "/form.txt",
"label" : "修改",
"type" : "primary",
"isApi" : false,
"useid" : 0
},
{
"action" :"disable",
"label" : ["禁用导航","启用导航"],
"urls" : ["/form1.txt","/form2.txt"],
"type" : ["warning","success"],
"isApi" : true,
"useid" : 0,
"switch" : true,
"switchKey": "status"
},
{
"action" :"delete",
"confirm" : {
"msg" : "确定删除选中数据?"
},
"label" : "删除",
"url" : "/form.txt",
"type" : "danger",
"isApi" : true,
"useid" : 0,
"canDisable" : true,
"disableKey" : "num"
}
]
},
"title" : "树状表格中心",
"currentView" : "KTreer"
}
package.json 命令
"mock": "json-server --watch mock/db.js"
启动服务 localhost:3000/tree
注意:
- json-server的访问方式get和post大有不同。。。坑
进阶用法请看→json-server-api
更多推荐
已为社区贡献1条内容
所有评论(0)