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 全支持
支持分页筛选排序 非常适合模拟真实后端接口
可扩展 支持中间件、自定义路由等高级功能

相关推荐
中年程序员一枚14 小时前
多数据源的springboot进行动态连接方案
java·spring boot·后端
w***765514 小时前
SpringBoot集成MQTT客户端
java·spring boot·后端
HABuo14 小时前
【Linux进程(五)】进程地址空间深入剖析-->虚拟地址、物理地址、逻辑地址的区分
linux·运维·服务器·c语言·c++·后端·centos
IT_陈寒15 小时前
SpringBoot 3.x实战:5个高效开发技巧让我减少了40%重复代码
前端·人工智能·后端
悟空码字15 小时前
三步搞定短信验证码!SpringBoot集成阿里云短信实战
java·spring boot·后端
嘉然今天吃粑粑柑15 小时前
Kafka vs RabbitMQ:从消费模型到使用场景的一次讲清
后端
肥肥今天也好看15 小时前
Java 日期格式化陷阱:YYYY vs yyyy 导致的生产事故分析
后端
用户9483570165115 小时前
可观测性落地:如何在 Java 项目中统一埋点 Trace ID?(一)
后端
天天摸鱼的java工程师15 小时前
volatile 关键字底层原理:为什么它不能保证原子性?
java·后端
leikooo15 小时前
SpringAI 多轮对话报错 400 Bad Request
后端·ai编程