json-server: 快速轻量的restful 风格的 mock服务器
json-server: 快速轻量的restful 风格的 mock服务器
-
安装 依赖 json-server
npm i json-server --save-dev
-
在项目根目录新建一个目录:
__json_server_mock__
目录前后的两个下划线是表示 这个目录中的内容跟 项目本身没有直接关系,只是作为辅助作用存在
-
在目录
__json_server-mock__
中新建 文件db.json
用来存储mock数据
在
db.json
中添加数据{ "users": [ { "id": 1, "name": "高修文" }, { "id": 2, "name": "熊天成" } ], "projects": [ { "id": 1, "name": "骑手管理", "personId": 1, "organization": "外卖组", "created": 1604989757139 } ] }
在之后使用过程中再自行添加
-
启动 json-server
-
json-server __json_server_mock__/db.json --watch
-
在 package.json 的 scripts 中添加脚本
"json-server": "json-server __json_server_mock__/db.json --watch --port 4000"
在命令行中开启服务
npm run json-server
-
-
Restful 风格api
1. GET /tickets // 获取列表 2. GET /tickets/12 // 详情 3. POST /tickets // 新增 4. PUT /tickets/12 // 替换 5. PATCH /tickets/12 // 修改 6. DELETE /tickets/12 // 删除
-
json-server是符合restful规范的服务,实际开发中不可能所有接口都符合restful规范,所以需要中间件middleware来模拟接口api
module.exports = ( req, res, next ) => { if(req.method === 'POST' && req.url === '/login'){ if(req.body.username === 'czx' && req.body.password === '123456'){ return res.status(200).json({ user: { token: '123' }}) }else{ return res.status(400).json({ message: '用户名或密码错误'}) } } next() }
package.json
的scripts
脚本中,进行修改,增加--middlewares __json_server_mock__/middleware.js
"json-server": "json-server __json_server_mock__/db.json --watch --port 4000 --middlewares __json_server_mock__/middleware.js"
-
增加数据
axios({ method: "post", url: "http://localhost:3000/list", data: { username: "王武", age: 18, }, }).then((data) => { console.log(data); });
-
删除某一条
axios({ method: "delete", url: "http://localhost:3000/list/1", //直接写ID即可 }).then((data) => { console.log(data); });
-
修改数据
axios({ method: "patch", url: "http://localhost:3000/list/3", //ID data: { username: "嘻嘻", //要修改成什么 }, }).then((data) => { console.log(data); });
-
查找所有
axios({ method: "get", url: "http://localhost:3000/list", }).then((data) => { console.log(data); });
-
查找指定某一条
axios({ method: "get", url: "http://localhost:3000/data/3", }).then((data) => { console.log(data); });
-
根据给定的 name 查找
axios({ method: "get", url: "http://localhost:3000/list?username=小猴", }).then((data) => { console.log(data); });
-
模糊查找
axios({ method: "get", url: "http://localhost:3000/data?q=小猴", }).then((data) => { console.log(data); });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2020-12-22 vue 过滤器