1. 全局安装指令:npm install -g json-server
2. 创建test.json 写入代码
{
"posts": [
{
"id": 1,
"title": "111",
"author": "typicode"
},
{
"id": 2,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
},
{
"id": 2,
"body": "some comment",
"postId": 2
}
],
"profile": {
"name": "typicode"
}
}
3. cd 存放json文件的目录;例如 cd Desktop
4. 进入指令:json-server --watch test.json
5. 在Home.js组件中请求数据
import React from 'react'
import { Button } from 'antd'
import axios from 'axios'
export default function Home() {
const ajax = () => {
//取数据 get
axios.post("http://localhost:3000/posts/2").then((res) => {
console.log(res);
})
//增加 post
// axios.post("http://localhost:3000/posts", {
// title: "333",
// athor: "juejue"
// })
//更新 patch
// axios.patch("http://localhost:3000/posts/1", {
// title: "111-修改"
// })
//删除 delete 会联动新闻posts的外键comments一起删除
// axios.delete("http://localhost:3000/posts/1")
//取数据get 通过新闻找到关联的评论 _embed 向下关联 请求新闻posts数据 comments会成为其中一项
// axios.get('http://localhost:3000/posts?_embed=comments').then(
// res => {
// console.log(res.data);
// }
// )
//取数据get 通过评论找到关联的新闻 _expand 向上关联 请求comments数据 posts会成为其中一项
// axios.get('http://localhost:3000/comments?_expand=post').then(
// res => {
// console.log(res.data);
// }
// )
}
return (
<div>
<Button type="primary" onClick={ajax}>Button</Button>
</div>
)
}