JSON Server 详细使用教程

简介

JSON Server 是一个非常实用的工具,可以让你快速搭建一个模拟 REST API。它可以基于一个 JSON 文件快速创建一个全功能的假 REST API,非常适合前端开发时做原型或 mock 数据。本文将详细介绍 JSON Server 的安装和使用方法。

安装

JSON Server 是一个 Node.js 模块,可以通过 npm 安装:

复制代码
npm install -g json-server
创建 JSON 数据文件

首先创建一个 JSON 文件,例如 db.json:

复制代码
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}
启动服务器

在命令行中,进入 db.json 所在目录,运行:

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

现在,你就可以通过 http://localhost:3000 访问你的 API 了。

API 路由

JSON Server 会根据你的 JSON 文件自动生成以下路由:

  • GET /posts
  • GET /posts/1
  • POST /posts
  • PUT /posts/1
  • PATCH /posts/1
  • DELETE /posts/1

类似地,其他顶级属性(如 comments, profile)也会生成对应的路由。

高级用法

自定义路由

你可以创建一个 routes.json 文件来自定义路由:

复制代码
{
  "/api/*": "/$1",
  "/:resource/:id/show": "/:resource/:id",
  "/posts/:category": "/posts?category=:category",
  "/articles\\?id=:id": "/posts/:id"
}

然后启动服务器时使用 --routes 选项:

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

使用中间件

你可以使用 JSON Server 的中间件来添加自定义逻辑。创建一个 middleware.js 文件:

javascript 复制代码
module.exports = (req, res, next) => {
  if (req.method === 'POST') {
    req.body.createdAt = Date.now()
  }
  next()
}

然后在启动服务器时使用 --middlewares 选项:

javascript 复制代码
json-server db.json --middlewares ./middleware.js

生成随机数据

JSON Server 使用 Faker.js 来生成随机数据。你可以在 db.json 中使用 JS 代码来生成数据:

javascript 复制代码
module.exports = () => {
  const data = { users: [] }
  for (let i = 0; i < 50; i++) {
    data.users.push({ id: i, name: `user${i}` })
  }
  return data
}

全文搜索

JSON Server 支持全文搜索,只需在 GET 请求中添加 q 参数:

javascript 复制代码
GET /posts?q=internet

关系

你可以在资源之间建立父子关系:

javascript 复制代码
GET /posts/1/comments
POST /posts/1/comments

分页

JSON Server 默认支持分页,使用 _page_limit 参数:

javascript 复制代码
GET /posts?_page=7&_limit=20

部署

JSON Server 可以很容易地部署到各种平台,如 Heroku、Now 等。你只需要创建一个简单的 server.js 文件:

javascript 复制代码
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(3000, () => {
  console.log('JSON Server is running')
})

然后按照各平台的部署指南进行部署即可。

总结

JSON Server 是一个强大而灵活的工具,可以快速创建模拟 REST API。它不仅适用于前端开发的原型设计和测试,也可以用于后端开发的 API 设计和文档编写。通过本教程,你应该能够掌握 JSON Server 的基本使用方法,并能够根据需要进行更高级的配置和使用。

相关推荐
键盘鼓手苏苏21 小时前
Flutter for OpenHarmony 实战:Flutter Rust Bridge — 极致计算性能方案
开发语言·后端·flutter·华为·rust·json·harmonyos
攻城狮的梦1 天前
go中json数据的转化
json
Dxy12393102162 天前
Python检查JSON格式错误的多种方法
前端·python·json
秃了也弱了。2 天前
python修复json神器:json-repair包(用于大模型返回json不规范)
python·json
I'm Jie2 天前
【已解决】SqlAlchemy 插入 MySQL JSON 字段时 None 变为 ‘null‘ 字符串,WHERE IS NULL 失效
数据库·python·mysql·json·fastapi·sqlalchemy
Hui Baby2 天前
Spring Boot 中使用 JSONPath 高效处理 JSON 数据
spring boot·python·json
Hui Baby2 天前
SpringBoot + JSON 字段 + MySQL 8.0 函数索引:灵活存储半结构化数据,查询不慢
spring boot·mysql·json
Dxy12393102163 天前
Python 将 JSON 字符串转换为字典
前端·python·json
一个天蝎座 白勺 程序猿4 天前
破译JSON密码:KingbaseES全场景JSON数据处理实战指南
数据库·sql·json·kingbasees·金仓数据库
叫我龙翔4 天前
【计网】从零开始掌握序列化 --- JSON实现协议 + 设计 传输\会话\应用 三层结构
服务器·网络·c++·json