用JSON-server模拟REST API(一) 安装运行

在开发过程当中,先后端不管是否分离,接口多半是滞后于页面开发的。因此创建一个REST风格的API接口,给前端页面提供虚拟的数据,是很是有必要的。前端

对比过多种mock工具后,我最终选择了使用 json server 做为工具,由于它足够简单,写少许数据,便可使用。
也由于它足够强大,支持CORS和JSONP跨域请求,支持GET, POST, PUT, PATCH 和 DELETE 方法,更提供了一系列的查询方法,如limit,order等。下面我将详细介绍 json server 的使用。node

安装

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

npm install json-server -g

使用linux和macOS的电脑须要加上sudolinux

sudo npm install json-server -g

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

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
github

{
  "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 文件,写入ajax

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

而后使用到 /mock 目录下执行 npm run mock 命令,若是成功会出现npm

> @ 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 文件的格式是否正确。json

操做数据

GET

这个时候访问 http://localhost:3003/db 能够查看 db.json 文件中所定义的所有数据。
使用浏览器地址栏,jQuery.getfecth({method: "get"}) 访问 http://localhost:3003/news ,则能够看到 news 对象下的数据,以Array格式返回:后端

[
  {
    "id": 1,
    "title": "曹县宣布昨日晚间登日成功",
    "date": "2016-08-12",
    "likes": 55,
    "views": 100086
  },
  {
    "id": 2,
    "title": "长江流域首次发现海豚",
    "date": "2016-08-12",
    "likes": 505,
    "views": 9800
  }
]

POST

以jquery的 $.ajax 方法举例,如下代码会实时的向 db.json 中的 news 对象push一条新的数据再次用 get 方式访问 http://localhost:3003/news , 就能够看到它了

$.ajax({
    type: 'post',
    url: 'http://localhost:3003/news',
    data: {
      "id": 3,
      "title": "我是新加入的新闻",
      "date": "2016-08-12",
      "likes": 0,
      "views": 0
    }
  }
)

PUT

一样以jquery的 $.ajax 方法举例,如下代码会实时的对 db.json 中的 news 对象中 id=1 数据进行修改

$.ajax({
    type: 'put',
    url: 'http://localhost:3003/news/1',
    data: {
      "title": "曹县宣布昨日晚间登日失败",
      "date": "2016-08-12",
      "likes": 55,
      "views": 100086
    }
  }
)

// 结果

[
  {
    "id": 1,
    "title": "曹县宣布昨日晚间登日失败",
    "date": "2016-08-12",
    "likes": 55,
    "views": 100086
  }
]

PATCH 和 DELETE 使用方式同上,就不作演示了。

参考资料

json-server源码 : json-server
mockjs源码 : mockjs
demo : 示例代码

相关文章
相关标签/搜索