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

相关推荐
阑梦清川2 小时前
关于Go语言的开发环境的搭建
开发语言·后端·golang
lyrhhhhhhhh2 小时前
Spring 模拟转账开发实战
java·后端·spring
tonngw2 小时前
【Mac 从 0 到 1 保姆级配置教程 12】- 安装配置万能的编辑器 VSCode 以及常用插件
git·vscode·后端·macos·开源·编辑器·github
半路_出家ren2 小时前
python处理异常,JSON
python·json·异常处理
noravinsc3 小时前
InforSuite RDS 与django结合
后端·python·django
Brookty4 小时前
【MySQL】基础知识
后端·学习·mysql
一只码代码的章鱼4 小时前
Spring 的 异常管理的相关注解@ControllerAdvice 和@ExceptionHandler
java·后端·spring
老友@5 小时前
Spring Data Elasticsearch 中 ElasticsearchOperations 构建查询条件的详解
java·后端·spring·elasticsearch·operations
熬夜苦读学习5 小时前
Linux线程控制
linux·运维·服务器·开发语言·后端
bing_1586 小时前
Spring Boot 项目中什么时候会抛出 FeignException?
java·spring boot·后端