目录

json-server 是一个轻量级的 REST API 服务器,它使用一个简单的 JSON 对象来存储数据,并提供了一套完整的 CRUD (创建、读取、更新、删除) 操作。它非常适合用于快速原型开发、测试或学习 RESTful API。

1. 安装

首先,您需要安装 json-server。通过 npm 全局安装是最简单的方法:

1
2
3
4
bash

 代码解读
复制代码npm install -g json-server

2. 启动服务器

创建一个 db.json 文件,这将作为我们的数据库。例如:

1
2
3
4
5
6
json 代码解读复制代码{
  "users": [
    { "id": 1, "name": "Alice", "age": 30 },
    { "id": 2, "name": "Bob", "age": 25 }
  ]
}

使用 json-server 启动服务器:

1
2
3
4
bash

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

这将启动一个默认监听在 3000 端口的服务器。

错误处理

如果在启动的时候遭遇到如下报错:

1
2
3
plainText 代码解读复制代码import { parseArgs } from 'node:util'; 
         ^^^^^^^^^
SyntaxError: The requested module 'node:util' does not provide an export named 'parseArgs'

很有可能是使用的 node 版本过低,这个时候需要升级 node 到至少 16 之上:

  1. 更新 Node.js: 确保您的 Node.js 版本是最新的或至少满足 json-server 的最低版本要求。您可以通过运行 node -v 来检查当前的 Node.js 版本,并通过 npm install -g n 安装 n 版本管理器来方便地切换 Node.js 版本。

  2. 检查 json-server 版本: 如果您的 Node.js 版本是最新的,确保您安装的 json-server 是兼容的版本。您可以通过运行以下命令来检查 json-server 的版本:

    1
    2
    3
    4
    
    css
    
     代码解读
    复制代码bashjson-server --version
    

    如果版本过旧,您可以通过以下命令更新它:

    1
    2
    3
    4
    
    bash
    
     代码解读
    复制代码npm install -g json-server@latest
    
  3. 使用 nvm 安装特定版本的 Node.js: 如果您需要使用特定版本的 Node.js,可以使用 nvm(Node Version Manager)来安装并管理多个 Node.js 版本。安装 nvm 后,您可以使用以下命令安装并使用特定版本的 Node.js:

    1
    2
    
    bash 代码解读复制代码nvm install 16 # 安装 Node.js 16 版本
    nvm use 16     # 使用 Node.js 16 版本
    

3. RESTful 接口实现

json-server 为我们提供了以下 RESTful API 接口:

  1. GET /resource - 列出所有资源
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
bash

 代码解读
复制代码curl http://localhost:3000/users
ts 代码解读复制代码import axios from 'axios';

async function getAllUsers() {
  try {
    const response = await axios.get('http://localhost:3000/users');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching users:', error);
  }
}
  1. GET /resource/id - 根据 ID 获取单个资源
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
bash

 代码解读
复制代码curl http://localhost:3000/users/1
ts 代码解读复制代码async function getUserById(id: number) {
  try {
    const response = await axios.get(`http://localhost:3000/users/${id}`);
    console.log(response.data);
  } catch (error) {
    console.error(`Error fetching user with id ${id}:`, error);
  }
}
  1. POST /resource - 创建新资源
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
bash

 代码解读
复制代码curl -X POST -H "Content-Type: application/json" -d '{"name":"Carol","age":22}' http://localhost:3000/users
ts 代码解读复制代码async function createUser(user: { name: string, age: number }) {
  try {
    const response = await axios.post('http://localhost:3000/users', user);
    console.log(response.data);
  } catch (error) {
    console.error('Error creating user:', error);
  }
}
  1. PUT /resource/id - 更新资源
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
bash

 代码解读
复制代码curl -X PUT -H "Content-Type: application/json" -d '{"name":"Alice","age":31}' http://localhost:3000/users/1
ts 代码解读复制代码async function updateUser(id: number, updates: Partial<{ name: string, age: number }>) {
  try {
    const response = await axios.put(`http://localhost:3000/users/${id}`, updates);
    console.log(response.data);
  } catch (error) {
    console.error(`Error updating user with id ${id}:`, error);
  }
}
  1. DELETE /resource/id - 删除资源
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
bash

 代码解读
复制代码curl -X DELETE http://localhost:3000/users/1
ts 代码解读复制代码async function deleteUser(id: number) {
  try {
    const response = await axios.delete(`http://localhost:3000/users/${id}`);
    console.log(response.data);
  } catch (error) {
    console.error(`Error deleting user with id ${id}:`, error);
  }
}

4. 自定义路由

json-server 也支持自定义路由。在命令行中使用 --router 选项指定自定义路由文件:

1
2
3
4
bash

 代码解读
复制代码json-server --watch db.json --router routes.json

routes.json 文件可能如下:

1
2
3
4
5
json 代码解读复制代码{
  "/users": "/users",
  "/users/:id/increment_age": "/users/:id",
  "/products/:id/reviews": "/products/:id/reviews"
}

5. 中间件

json-server 允许你使用中间件来处理请求前后的逻辑。例如,我们可以添加一个中间件来记录每个请求:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
javascript 代码解读复制代码const jsonServer = require('json-server');

const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();

server.use(middlewares);

server.post('/users', (req, res, next) => {
  console.log('Received a POST request');
  next();
});

// 使用自定义路由
server.use(jsonServer.rewriter({ '/products/:id/reviews': '/products/:id/reviews' }));

server.listen(3000, () => {
  console.log('JSON Server is running');
});

6. 总结

json-server 是一个非常有用的工具,可以快速搭建 RESTful API 服务器,无需编写后端代码。它不仅简化了开发流程,还为开发者提供了一个学习 RESTful API 的优秀环境。通过本文的介绍,你应该能够快速启动和使用 json-server,并利用它构建你的应用程序后端。