1、下载
cnpm install -D [email protected]
2、使用
(1)创建.json文件添加属性
localhost:3000/键名
localhost:3000/键名/id值返回对应的字段
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
或者使用postman,在请求数据的时候带上json数据,即可往文件中添加数据
(2)开启服务
json-server -w --port 端口名称默认为3000 json文件路径
(3)请求接口,会根据请求返回内容动态修改json文件里的内容
通过请求方法的不同,模拟对数据的增删改查
使用postman也是根据请求的字段进行,x-www-form-urlencoded方式进行参数的携带
增加数据
axios({
method:"post",
url:"http://localhost:3000/键名",
data:{
username:"Yi只猴",
age:18
}
}).then((data)=>{
console.log(data)
})
删除某一条
axios({
method:'delete',
url:'http://localhost:3000/键名/id值'
}).then((data)=>{
console.log(data)
})
修改数据
axios({
method:"patch",
url:"http://localhost:3000/data/3",//ID
data:{
username:'嘻嘻' //要修改成什么
}
}).then((data)=>{
console.log(data)
})
根据指定字段查找
axios({
method:"get",
url:"http://localhost:3000/data?username=小猴",
}).then((data)=>{
console.log(data)
})
(4)添加中间件提前处理请求
创建.js文件
module.exports=(req,res,next)=>{
req.method 请求方法
req.path 请求路径
req.body POST请求参数
return res.status(200).json({...}) 返回数据
next(); 最后需要调用next()跳转到下一个中间件
}
注意:fetch请求需要添加headers
headers: {
'Content-Type':'application/json'
},
启用中间件:在命令中添加 --middlewares 文件路径
json-server(模拟后端接口请求)
猜你喜欢
转载自blog.csdn.net/weixin_43294560/article/details/114848272
今日推荐
周排行