概述
前后端分离开发是当前大多数公司的一种模式,这样让开发者更加专注于某一方向。但是在实际的工作中,很容易出现前端后端互等的情况,一方面不利于沟通,另一方面降低了开发效率。在很多公司的业务都是前端驱动的,所以前端人员可以根据业务先定义数据结构先行开发。本文基于json-server
搭建一个mock
接口。
json-server
简介
json-server
是一款小巧的Mock工具,它可以不写一行代码在30秒内创建一套Restful风格的 api,适合3人及以下的前端团队做迅速mock后台逻辑,也可以在接口测试中使用。
实现效果
image.png实现
1. 初始化工程
npm init -y
2.添加依赖
npm i json-server -D
3. 添加启动
# 修改package.json文件
"scripts": {
"mock": "json-server --watch ./mock_server/db.json --id key --p 13000"
},
在根目录下创建mock_server/db.json
文件,文件内容如下:
{
"users": [
{
"key": 11,
"name": "KevinChen"
},
{
"key": 12,
"name": "KevinChen"
},
{
"key": 13,
"name": "KevinChen"
},
{
"key": 14,
"name": "KevinChen"
},
{
"key": 15,
"name": "KevinChen"
},
{
"key": 16,
"name": "KevinChen"
},
{
"key": 17,
"name": "KevinChen"
},
{
"key": 18,
"name": "KevinChen"
}
],
"dept": [
{
"title": "西安分公司",
"key": "xian",
"checkable": false,
"isDept": true,
"children": [
{
"title": "张叁",
"key": "张叁"
},
{
"title": "李四",
"key": "李四"
},
{
"title": "王五",
"key": "王五"
}
]
},
{
"title": "上海分公司",
"key": "shanghai",
"isDept": true,
"checkable": false,
"children": [
{
"title": "刘平",
"key": "刘平"
},
{
"title": "陈辰",
"key": "陈辰"
},
{
"title": "何夕",
"key": "何夕"
}
]
}
]
}
4.调用接口
# 获取数据 get
http://localhost:13000
http://localhost:13000/users
http://localhost:13000/users?_page=1&_limit=4 // 分页
http://localhost:13000/dept
http://localhost:13000/dept/xian // 根据id查询
http://localhost:13000/dept?title=西安分公司 // 根据条件查询
# 新增数据 post
http://localhost:13000/dept JSON(application/json)
{
"title": "北京分公司",
"key": "beijing",
"checkable": false,
"isDept": true,
"children": [
{
"title": "张叁",
"key": "张叁"
},
{
"title": "李四",
"key": "李四"
},
{
"title": "王五",
"key": "王五"
}
]
}
# 修改数据 patch
http://localhost:13000/dept/beijing JSON(application/json)
{
"title": "北京分公司",
"key": "beijing",
"checkable": false,
"isDept": true,
"children": [
{
"title": "张叁",
"key": "张叁"
},
{
"title": "李四",
"key": "李四"
},
{
"title": "王五",
"key": "王五"
}
]
}
# 删除数据 delete
http://localhost:13000/dept/beijing
网友评论