json-server搭建使用

项目中前端和后端通常是并行开发,为了减少等待后端接口开发的时间,我们经常需要在本地模拟后端接口用来测试前端效果。这种做法称之为构建前端Mock。

  1. 本地启动一个静态服务,将所需要的接口写成json文件,根据接口名字将文件放在项目目录下。
  2. 再启动一个Server作为Mock Server,使用第三方Proxy将Mock Server的接口代理到静态服务器上。

30秒内创建完整的REST API

安装

首先你的电脑中需要安装nodejs,建议使用最新版本。然后全局安装json server.

npm install json-server -g

使用linux和macOS的电脑需要加上sudo

sudo npm install json-server -g

安装完成后可以用 json-server -h 命令检查是否安装成功,成功后会出现

json-server [options] <source>

选项:
  --config, -c       Path to config file            [默认值: "json-server.json"]
  --port, -p         Set port                                     [默认值: 3000]
  --host, -H         Set host                                [默认值: "0.0.0.0"]
  --watch, -w        Watch file(s)                                        [布尔]
  --routes, -r       Path to routes file
  --static, -s       Set static files directory
  --read-only, --ro  Allow only GET requests                              [布尔]
  --no-cors, --nc    Disable Cross-Origin Resource Sharing                [布尔]
  --no-gzip, --ng    Disable GZIP Content-Encoding                        [布尔]
  --snapshots, -S    Set snapshots directory                       [默认值: "."]
  --delay, -d        Add delay to responses (ms)
  --id, -i           Set database id property (e.g. _id)          [默认值: "id"]
  --quiet, -q        Suppress log messages from output                    [布尔]
  --help, -h         显示帮助信息                                         [布尔]
  --version, -v      显示版本号                                           [布尔]

示例:
  json-server db.json
  json-server file.js
  json-server http://example.com/db.json

https://github.com/typicode/json-server

运行

安装完成后,可以在任一目录下建立一个 xxx.json 文件,例如在 mock/ 文件夹下,建立一个 db.json 文件,并写入以下内容,并在 mock/ 文件夹下执行 json-server db.json -p 3003 。

{
  "news":[
    {
      "id": 1,
      "title": "曹县宣布昨日晚间登日成功",
      "date": "2016-08-12",
      "likes": 55,
      "views": 100086
    },
    {
      "id": 2,
      "title": "长江流域首次发现海豚",
      "date": "2016-08-12",
      "likes": 505,
      "views": 9800
    }
  ],
  "comments":[
    {
      "id": 1,
      "news_id": 1,
      "data": [
        {
          "id": 1,
          "content": "支持党中央决定"
        },
        {
          "id": 2,
          "content": "抄写党章势在必行!"
        }
      ]
    }
  ]
}

为了方便,再创建一个 package.json 文件,写入

{
  "scripts": {
    "mock": "json-server db.json --port 3003"
  }
}

然后使用到 /mock 目录下执行 npm run mock 命令,如果成功会出现

> @ mock /你的电脑中mock文件夹所在目录的路径/mock
> json-server db.json -p 3003


  {^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3003/news
  http://localhost:3003/comments

  Home
  http://localhost:3003

如果不成功请检查 db.json 文件的格式是否正确。

原文地址:https://www.cnblogs.com/xiaomili/p/7859969.html