可以用来模拟接口,并且带有增删改查的功能
安装
npm install -g json-server
1.在项目目录外新建一个文件夹 名为db
,
2.然后新建一个test.json
文件
//文件格式
{
"posts": [
{
"id": 1,
"title": "1111-修改-111",
"author": "typicode"
},
{
"id": 2,
"title": "json-server2",
"author": "typicode2"
},
{
"id": 3,
"title": "123",
"author": "cqj"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
},
{
"id": 2,
"body": "some comment2",
"postId": 2
}
]
}
3.shift 右键 打开powerShell
窗口 键入json-server --watch .\test.json --port 8000
4.启动成功后,就可以看到json文件生成的所有接口了
页面中使用
/*
* @Version: 2.0
* @Autor: CQJ
* @Date: 2022-03-31 17:13:28
* @LastEditTime: 2022-04-02 16:55:04
* @LastEditors: CQJ
* @Description:
*/
import { Button } from "antd";
import axios from "axios";
import React from "react";
export default function Home() {
const ajax = () => {
// 增加数据 post
axios
.post("http://localhost:8000/posts", {
title: "123",
author: "cqj1",
})
.then((res) => {
console.log("res: ", res.data);
});
// 修改数据 put(替换式更新)
axios
.put("http://localhost:8000/posts/1", {
title: "1111-修改",
author: "cqj",
})
.then((res) => {
console.log("res: ", res.data);
});
// 更新数据 patch(局部更新)
axios.patch("http://localhost:8000/posts/1", {
title: "1111-修改-111",
});
.then((res) => {
console.log("res: ", res.data);
});
// 取数据 get
axios.get("http://localhost:8000/posts").then((res) => {
console.log("res: ", res.data);
});
// 删除数据 delete
axios.delete("http://localhost:8000/posts/4").then((res) => {
console.log("res: ", res.data);
});
// _embed 携带相关id的数据向下查找 根据posts结构下id为1的查找comments结构中id为1的,合并到返回数据中
axios.get("http://localhost:8000/posts?_embed=comments").then((res) => {
console.log("res: ", res.data);
});
//_expand post postId 有关联 根据postId向上查找合并到comments 返回
axios.get("http://localhost:8000/comments?_expand=post").then((res) => {
//能通过comments结构下id为1的数据,查找到posts结构下id为1的数据合并到返回数据中
console.log("res: ", res.data);
});
};
return (
<div>
<Button type="primary" onClick={ajax}>
Primary Button
</Button>
</div>
);
}