json-server的用法-基于 RESTful API 的本地 mock 服务

json-server 是一个非常方便的工具,用于快速搭建基于 RESTful API 的本地 mock 服务,特别适合前端开发阶段模拟后端数据接口。


🧩 一、安装

bash 复制代码
npm install -g json-server

🚀 二、快速启动

  1. 创建一个 db.json 文件(模拟数据库):
json 复制代码
{
  "posts": [
    { "id": 1, "title": "Hello", "author": "Tom" },
    { "id": 2, "title": "Hi", "author": "Jerry" }
  ],
  "comments": [
    { "id": 1, "body": "Nice post!", "postId": 1 }
  ],
  "profile": { "name": "User" }
}
  1. 启动服务:
bash 复制代码
json-server --watch db.json

默认运行在:

📍 http://localhost:3000


🔧 三、支持的 RESTful API 操作

假设资源名为 posts

操作 请求方式 路径 描述
获取列表 GET /posts 获取所有 posts
获取单个 GET /posts/1 获取 id 为 1 的 post
创建数据 POST /posts 添加新 post(需传 JSON)
更新(整体) PUT /posts/1 替换整个 post 对象
更新(部分) PATCH /posts/1 修改 post 的部分字段
删除 DELETE /posts/1 删除 post

🎛️ 四、常用功能说明

1. 分页、筛选、排序

  • 分页:?_page=2&_limit=10
  • 排序:?_sort=title&_order=desc
  • 筛选:?author=Tom

例如:

复制代码
GET /posts?_page=1&_limit=5&_sort=title&_order=asc&author=Tom

2. 模糊查询

复制代码
GET /posts?q=hello

模糊匹配所有字段包含 "hello" 的数据。

3. 关联查询(联表)

支持嵌套数据查询,例如:

复制代码
GET /comments?postId=1
GET /posts/1?_embed=comments
  • _embed=comments:获取 post 时嵌入其 comments
  • _expand=post:获取 comment 时展开其对应 post

⚙️ 五、自定义路由(可选)

新建 routes.json

json 复制代码
{
  "/api/*": "/$1"
}

然后运行:

bash 复制代码
json-server --watch db.json --routes routes.json

效果:

访问 /api/posts 实际映射到 /posts


🛡️ 六、中间件与端口指定(高级用法)

bash 复制代码
json-server --watch db.json --port 4000 --middlewares ./middleware.js

也可以使用 node 脚本自定义服务:

js 复制代码
// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

server.use(middlewares)
server.use(router)
server.listen(4000, () => {
  console.log('JSON Server is running')
})

运行:

bash 复制代码
node server.js

🧪 七、开发中典型用途

  • 前端开发模拟 API,无需后端配合
  • Mock 数据开发接口文档
  • 演示项目/原型展示

✅ 八、总结亮点

特点 描述
零配置启动 基于一个 JSON 文件即可构建完整 RESTful API
完全 RESTful GET/POST/PUT/PATCH/DELETE 全支持
支持分页筛选排序 非常适合模拟真实后端接口
可扩展 支持中间件、自定义路由等高级功能

相关推荐
ShadowYD10 小时前
Agent Loop:一个让 AI 编程 Agent 从"会写代码"进化到"闭环交付"的开源 Skill(适配国内外主流 Code Agent)
后端
考虑考虑11 小时前
nohup启动java程序
后端·自动化运维
aramae12 小时前
模拟实现strcmp()(C语言)
c语言·开发语言·后端
根目录下的猫14 小时前
RK3588适配的轻量级AI模型推荐
人工智能·后端·python·目标检测
星栈15 小时前
用 Rust 写 Agent 服务 -- adk-rust 上手记
后端·agent
杨运交16 小时前
[071][验证码模块]基于Spring拦截器的验证码认证设计思想
java·后端·spring
LucianaiB16 小时前
我用豆包工作 Seed-2.1-pro,复刻了 QQ 时代爆红的魔术图片
后端
码事漫谈16 小时前
智谱 ZCode 静默上传 Git 历史:48 小时信任危机复盘
后端
掘金码甲哥17 小时前
当对话模型遇上向量模型,vllm production stack 又该如何应对?
后端