【Node.js】json-server

146 阅读1分钟

概述

json-server 主要用于快速开启一个后端服务,并手动设置模拟接口数据。

以下来源于 json-server - npm (npmjs.com)

安装

npm install json-server

用法

创建文件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"
  }
}

将其传递给 JSON 服务器 CLI

$ npx json-server db.json

获取 REST API

$ curl http://localhost:3000/posts/1
{
  "id": "1",
  "title": "a title"
}

运行选项列表json-server --help

基于示例,将获得以下路由:db.json

GET    /posts
GET    /posts/:id
POST   /posts
PUT    /posts/:id
PATCH  /posts/:id
DELETE /posts/:id

# Same for comments
GET   /profile
PUT   /profile
PATCH /profile