json-server
,json-server
是一个在前端本地运行,可以存储json
数据的server
json-server官网:https://github.com/typicode/json-server#getting-started
1、全局安装
1.1使用npm
全局安装json-server
:
npm install -g json-server
1.2通过查看版本号,来测试是否安装成功:
json-server -v
D:\Desktop\vue\code\sever>npm install -g json-server
added 205 packages, removed 63 packages, and changed 110 packages in 13s
D:\Desktop\vue\code\sever>json-server -v
0.17.3
2、 创建json数据
2.1初次运行
在任意一个文件夹下,在命令行执行代码,会自动在文件夹下创建出一个db.json
文件
json-server --watch db.json
D:\Desktop\vue\code\sever>json-server --watch db.json
\{^_^}/ hi!
Loading db.json
Oops, db.json doesn't seem to exist
Creating db.json with some default data
Done
Resources
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
Home
http://localhost:3000
根据结果提示,可以在浏览器中访问 http://localhost:3000
2.2再次启动命令
json-server --watch db.json
3、修改端口号
从上面启动日志可以看到,json-server
默认是3000
端口,但也可以自己指定端口,指令如下:
json-server --watch db.json --port 3001
上面的启动命令有点长,可以考虑使用package.json
文件来管理启动命令,在db.json
同级文件夹下新建一个package.json
,编写如下配置信息:
{
"scripts": {
"mock": "json-server db.json --port 3001"
}
}
再启动服务时只需要执行如下指令
npm run mock
4、 简单使用
4.1准备页面
<el-button type="success"
@click="getUserInfo()">查询</el-button>
<el-button type="success"
@click="addUserInfo()">增加</el-button>
<el-button type="success"
@click="modifyUserInfo()">修改</el-button>
<el-button type="success"
@click="deleteUserInfo()">删除</el-button>
4.2请求数据
4.2.1查询全部数据
getUserInfo () {
axios.get("http://localhost:3000/posts").then(res => {
console.log(res);
})
},
4.2.2根据查询id
getUserInfo () {
axios.get("http://localhost:3000/posts/1").then(res => {
console.log(res);
})
},
4.3增加数据
addUserInfo () {
const obj = {
uname: "添加张三",
pwd: "123"
}
axios.post("http://localhost:3000/posts", obj).then(res => {
console.log(res);
})
},
4.4 根据id修改数据
modifyUserInfo () {
const obj = {
uname: "修改张三",
pwd: "123"
}
axios.put("http://localhost:3000/posts/7", obj).then(res => {
console.log(res);
})
},
4.5删除数据
deleteUserInfo () {
axios.delete("http://localhost:3000/posts/7").then(res => {
console.log(res);
})
}