一.JSON-server工具
-
json-server可以快速的模拟接口
-
它是一个基于nodejs的命令行工具
安装
-
npm i json-server -g
全局安装
使用
在项目src下新建mock文件,在mock文件下存放json文件
启动命令
1.cd到mock文件夹下 json-server --watch xxx.json --port 端口号
2.修改启动命令 去package.json 找到scriptc节点添加我们的json-server的启动命令别名
"scripts": {
"serve": "vue-cli-service serve",
下面就是
"niubi":"json-server --watch ./src/mock/data.json --port 8899",
上面就是
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
-
(例)在json文件中写入内容
{ "brands": [ {"id":1,"name":"宝马","ctime":"2020-02-02 10:10:10"}, {"id":2,"name":"奔驰","ctime":"2021-02-02 10:10:10"}, {"id":3,"name":"奥迪","ctime":"2022-02-02 10:10:10"} ] }
-
不能关闭命令行窗口
-
id一定是数字,这样id才能自增
axios的使用:
-
查询所有
-
查询单个
-
添加操作
-
删除操作
-
修改操作
实例代码
// - 查询所有
axios({
url:"http://localhost:8899/user",
method:"get",
}).then(res=>{
console.log(res.data);
})
// - 查询单个
axios({
url:"http://localhost:8899/user",
method:"get",
params:{
id:1, //随便写,但是id是唯一值,只能查到一条,
}
}).then(res=>{
console.log(res.data);
})
// - 添加操作
axios({
url:"http://localhost:8899/user",
method:"post",
data:{
id:1, //id可以不写,会自增,如有该id会报错
name: '奥拓',
cTime: new Date()
}
}).then(res=>{
console.log(res);
})
// - 删除操作
axios({
url:"http://localhost:8899/user/1", //1为id
method:"delete",
}).then(res=>{
console.log(res);
})
// - 修改操作
//patch 仅替换匹配项
axios({
url:"http://localhost:8899/user/2", //2为要修改的那条数据的id
method:"patch",
data:{
name:"传祺", //修改内容
}
}).then(res=>{
console.log(res);
})
//put 全部替换 删除之前除id所有内容
axios({
url:"http://localhost:8899/user/2",
method:"put",
data:{
name:"路虎",
}
}).then(res=>{
console.log(res);
})
// json-server提供模糊查询 字段_like
axios({
url:'http://localhost:3000/brands',
method:"get",
params:{
name_like: '奥'
}
}).then(res=>{
console.log(res.data)
})