mock后端假接口数据-JsonServer工具的使用

159 阅读1分钟

1.利用JsonServer模拟后端数据

  • 1.终端执行全局安装json-server命令:npm install -g json-server
  • 2.桌面新建一个文件夹,终端进入文件夹,执行命令初始化:npm init,初始化的过程中只需要给文件包命名,其他项都直接回车。
  • 3.进入文件夹执行:npm install json-server --save
  • 4.创建 db.json 文件
{
    "posts": [
        { "id": 1, "title": "111-新闻", "author": "王小明" },
        { "id": 2, "title": "222-新闻", "author": "刘二雷" },
        { "id": 3, "title": "333-新闻", "author": "王小明" },
        { "id": 4, "title": "444-新闻", "author": "张三" }
    ],
    "comments": [
        { "id": 1, "body": "111-评论", "postId": 1 },
        { "id": 2, "body": "222-评论", "postId": 2 },
        { "id": 3, "body": "333-评论", "postId": 3 },
        { "id": 4, "body": "444-评论", "postId": 4 }
    ]
}
  • 5.起服务命令:json-server --watch db.json --port 8000

image.png

2.项目请求 json-server 服务器数据

image.png

import React from 'react'
import { Button } from 'antd';
import axios from 'axios';
export default function Home() {
    const ajax = () =>{
        // 获取数据  get
        // axios.get("http://localhost:8000/posts/2").then(res=>{
        //     console.log(res.data);
        // })

        // 新增数据  post
        // axios.post("http://localhost:8000/posts",{
        //     title: "999",
        //     "author": "wyf"
        // })

        // 修改  put(替换式更新,会出现未更改的项直接干掉了)
        // axios.put("http://localhost:8000/posts/1",{
        //     title:"111-修改"
        // })

        // 修改  patch(补丁式更新)
        // axios.patch("http://localhost:8000/posts/1",{
        //     title:"111-修改-999"
        // })

        // 删除 delete   同时会删除关联的内容
        // axios.patch("http://localhost:8000/posts/2")

        // _embed 向下连接,通过新闻id获取到对应的新闻评论
        // axios.get("http://localhost:8000/posts?_embed=comments").then(res=>{
        //     console.log(res.data);
        // })

        // _expand 向上找
        axios.get("http://localhost:8000/comments?_expand=post").then(res=>{
            console.log(res.data);
        })

    }
    return (
        <div>
            <Button type="primary" onClick={ajax}>Button</Button>
        </div>
    )
}