1.全局下载安装
npm install -g json-server
2.查看版本
json-server --version
如果报错:json-server命令/函数 不存在,需要全局安装
3.创建模拟数据文件夹 mock 在其中写入数据的 json 文件
{
"one":[
{"name":"xixi","age":18}
]
}
4.基础快速启动
(1)cd 到mock 文件夹下
json-server --watch 你的json文件名字 --port 你的端口
json-server --watch data.json --port 8888
(2)直接命令启动
json-server --watch ./路径/json文件名字 --port 你的端口
json-server --watch ./src/mock/data.json --port 8888
5.项目配置启动
在package.json文件中 在 scripts 节点中设置你的启动命令——mock
使用命令:npm run mock
"scripts": {
"mock": "json-server --watch ./src/mock/data.json --port 8888",
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
6.增删查改
json-server对数据进行增删改查操作_祈澈菇凉的博客-优快云博客
6.0请求数据
使用get方法
//请求用户数据
$.ajax({
type:"GET",
url:"http://localhost:3000/users",
dataType:"json",
success:function (data) {
console.log(data, '请求成功')
},
error:function (err) {
console.log(data, '请求失败')
}
});
6.1查
使用get方法
修改id为1的user数据
$(".serch").click(function() {
//查询id=1
$.ajax({
type: "get",
url: "http://localhost:3000/users/1",
dataType: "json",
success: function(e) {
console.log(e, '请求成功')
},
error: function(e) {
console.log(e, '请求失败')
}
})
})
6.2增
使用post方法
$(".add").click(function() {
var newData = {
"name": "新加数据",
"phone": "123456789",
"email": "11357097537@qq.com",
"age": "45",
"id": 5,
"companyId": 3
};
$.ajax({
type: "post",
url: "http://localhost:3000/users",
data: newData,
success: function(data) {
console.log(data, '请求成功')
},
error: function(data) {
console.log(data, '请求失败')
}
})
})
6.3删
使用delete方法
删除id为4的数据
$(".delete").click(function() {
var delUserId=4;
$.ajax({
type:"DELETE",
url:"http://localhost:3000/users/"+delUserId,
dataType:"json",
success:function(data){
console.log(data)
alert("删除成功")
},
error:function(err){
console.error(err)
}
})
})
6.4改
使用put方法
修改id为1的user数据
$(".edit").click(function() {
var updateuser = {
"name": "王小婷要修改一下哦",
"phone": "123456789",
"email": "11357097537@qq.com",
"age": "20",
"id": 1,
"companyId": 1
};
$.ajax({
type: "PUT",
url: "http://localhost:3000/users/1",
data: updateuser,
success: function(data) {
console.log(data)
},
error: function(err) {
console.error(err)
}
})
})
本文详细介绍了如何使用json-server创建和管理模拟数据,包括全局安装、启动服务、配置项目启动、以及通过HTTP方法(GET、POST、PUT、DELETE)进行数据的增删查改操作。通过这个教程,读者可以快速搭建本地API接口用于前端开发测试。
737

被折叠的 条评论
为什么被折叠?



