一、什么是JSON-Server?
JSON-Server 是一个 Node 模块,运行 Express 服务器,可以指定一个 json 文件作为 api 的数据源。
二、JSON-Server的使用
全局安装:
cmd命令行窗口输入:
npm install -g json-server
使用:
首先准备一个json文件:test.json
格式如下:
{
"posts": [
{
"id": 1,
"title": "1111-修改-11111",
"author": "kk"
},
{
"id": 2,
"title": "22222",
"author": "tiechui"
},
{
"title": "33333",
"author": "xiaoming",
"id": 3
}
],
"comments": [
{
"id": 1,
"body": "11111-comment",
"postId": 1
},
{
"id": 2,
"body": "22222-comment",
"postId": 2
}
]
}
然后使用全局json-server命令,启动mock服务。
json-server --watch --port 8000 test.json
输出如下内容说明启动成功。
数据访问举例(增删改查)
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:"33333",
// author:"xiaoming"
// })
// 更新 put
// axios.put("http://localhost:8000/posts/1",{
// title:"1111-修改"
// })
// 更新 patch 只更新变化的,不变的不动
// axios.patch("http://localhost:8000/posts/1",{
// title:"1111-修改-11111"
// })
// 删除 delete
// axios.delete("http://localhost:8000/posts/1")
// _embed,取关联数组,向下
// 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>
)
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?