json-server 快速搭建REST API 服务器

★ 认识json-server 官方文档参考

	json-server 是一个非常流行的开源工具,用于快速搭建一个完整的 REST API 服务器。它使用 JSON 文件作为数据源,通过简单的配置即可模拟复杂的服务器功能,非常适合前端开发者在没有后端支持的情况下进行开发和测试。

★ 主要特性

  • 零编码:只需一个简单的 JSON 文件,你就可以创建一个完整的 API,无需编写任何后端代码。
  • 灵活性:支持 GET, POST, PUT, PATCHDELETE 请求,可以处理各种 RESTful 请求。
  • 即时变更:对 JSON 文件的任何修改都会即时反映在 API 返回中,无需重启服务器。
  • 路由定制:可以通过配置文件自定义路由,模拟各种 API 路径和行为。
  • 中间件支持:可以使用 Express 中间件来增加额外的功能,如添加 headers、静态文件服务等。
  • 低系统要求:由于其简单性,json-server 对系统资源的要求非常低,非常适合快速原型开发和小型项目。

★ 使用步骤

  • 1-安装 json-server (需要先安装node)
    npm install -g json-server
    
  • 2-创建一个 JSON 文件 eg:db.json
    {
      "posts": [
        { "id": "1", "title": "a title", "views": 100 },
        { "id": "2", "title": "another title", "views": 200 }
      ],
      "comments": [
        { "id": "1", "text": "a comment about post 1", "postId": "1" },
        { "id": "2", "text": "another comment about post 1", "postId": "1" }
      ],
      "profile": {
        "name": "typicode"
      }
    }
    
  • 3-创建一个用于存放静态文件的目录,通常命名为 publicstatic
  • 4-启动 json-server
    • 启动说明:

      1. 使用 --static 标志来指定静态文件目录。如果你没有指定,json-server 默认会查找名为 public 的目录
      2. API 数据由 db.json 提供,静态文件服务由 public 目录提供
      3. npx 是一个 npm 包运行器,它允许你运行在本地 node_modules 目录或远程仓库中的命令。使用 npx json-server 启动的方式不需要你全局安装 json-server
      
    • 启动方式一: 在 Powershell 窗口中运行

      json-server --watch [json文件所在路径] --static ./public
      
    • 启动方式二:

      npx json-server [json文件所在路径] --static ./public
      
  • 5-API接口说明
    • 索引页路由

      http://localhost:3000/
      
    • API 数据资源路由 (支持GET/POST/PATCH/DELETE)

      http://localhost:3000/posts
      http://localhost:3000/posts/1
      http://localhost:3000/comments
      http://localhost:3000/comments/1
      http://localhost:3000/profile
      
    • 静态文件资源路由

      http://localhost:3000/index.html
      http://localhost:3000/favicon.ico