json-server用来模拟RESTFUL接口,需严格按照RESTFUL请求规则使用,是一个基于node.js的命令行工具
传送门:https://github.com/typicode/json-server
安装:
npm i json-server -g
全局安装
使用:
新建一个文件夹,在文件夹中新建db.json文件
db.json文件内容(这里以一个接口为例):
其中"brands"为接口名,通过这一个列表接口,再搭配RESTFUL规则, 即可生成增删改查等多个接口
{
"brands": [
{
"id": 1,
"name": "宝马",
"time": "2020-06-02 21:50:03"
},
{
"id": 2,
"name": "奥迪",
"time": "2020-06-02T14:14:34.332Z"
},
{
"name": "宝宝",
"time": "2020-06-02T14:31:44.987Z",
"id": 3
}
]
}
执行:
在新建的文件夹下执行json-server db.json:
执行结果:
当出现这个标志,说明执行成功
通过http://localhost:3000/brands即可访问该列表接口
已经产生以下接口:
接口地址 | 请求方式 | 操作行为 |
/brands | GET | 查询所有列表 |
/brands/:id | GET | 查询单个详情 /brands/1 |
/brands | POST | 添加,提交的参数在请求体 |
/brands/:id | DELETE | 删除 /brands/1 |
/brands/:id | PUT | 修改 /brands/1 + 请求体{name,cTime} 全部修改 |
/brands/:id | PATCH | 修改 /brands/1 + 请求体{name} 个别修改 |
简单示例:
methods:{
// 查询列表
getAll(){
axios.get('http://127.0.0.1:3000/brands').then(res => {
this.list = res.data;//获取data
}).catch(err => {
console.log(err);
});
},
del(id){
if(confirm('是否删除?')){
axios.delete(`http://127.0.0.1:3000/brands/${id}`).then(res => {
//this.getAll();
}).catch(err => {
console.log(err);
});
}
},
save(){
if(!this.brand.trim())return alert('输入品牌');
axios.post('http://127.0.0.1:3000/brands',{
name:this.brand,
time:new Date()
}).then(res => {
//this.getAll();
//this.brand = '';
}).catch(err => {
console.log(err);
});
}
},
mounted(){
//这里使用vue转dom的方式
this.$refs.keyword.focus();
},
watch:{
keyword(){
axios.get('http://127.0.0.1:3000/brands',{params:{name_like:this.keyword}})
.then(res => {
this.list = res.data;
}).catch(err => {
console.log(err);
});
}
}
以后若使用到,会继续更新