利用 json-server 模拟接口
一、 安装依赖
npm install -g json-server
二、准备一个json文件,如命名db.json,附上官方:
{
"posts": [
{ "id": 1, "title": "新闻标题", "author": "Minnie" }
],
"comments": [
{ "id": 1, "body": "新闻评论", "postId": 1 }
],
"profile": { "name": "typicode" }
}
三、在该文件所在的文件夹打开终端,启动
json-server --watch db.json
json-server --watch ./db.json --port 3001
(或 指定某个端口)
四、前端使用
基础CRUD:
GET /posts
GET /posts/1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1
高级用法
// 向下关联(找到相关的评论)
axios.get('http://localhost:3001/posts?_embed=comments').then(res => {});
// 向上关联(找到评论相关的新闻)注意是'post'而不是'posts'
axios.get('http://localhost:3001/comments?_expand=post').then(res => {});
仅仅列举了个别常用的做法,具体请移步到 👉 官方