使用 json-server 作为 mock 数据

2,169 阅读2分钟

通常前端需要 mock API 数据来模拟接口请求,今天介绍一个牛B的 mock 数据的方法,那就是 json-server 这个包,我们可以在 30 秒内得到一个完整的 REST API,零编码。我们只要准备好 JSON 数据就可以了。

安装

npm install -g json-server

创建一个 db.json 文件和准备一些 data 数据。

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

启动

json-server --watch db.json

如果访问 http://localhost:3000/posts/1, 可以获取一条数据

{ "id": 1, "title": "json-server", "author": "typicode" }

如果你发送 POST、PUT、PATCH 或 DELETE 请求,更改数据将自动安全地保存到 db.json。

POST、PUT 或 PATCH 请求应该包含一个内容类型:application/json header,以便在请求体中使用 json。否则,它将返回一个2XX状态码,但不更改数据。

GET    /profile
POST   /profile
PUT    /profile
PATCH  /profile

过滤器,可以使用.访问深层属性。

GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
GET /comments?author.name=typicode

分页,可以使用 _page 和可选的 _limit 处理返回的分页数据。默认 10 条每页。

GET /posts?_page=7
GET /posts?_page=7&_limit=20

在请求 Response Header,您将获得 first、prev、next 和 last 表示的链接。

Link: <http://localhost:3000/blogs?_page=1&_limit=2>; rel="first", <http://localhost:3000/blogs?_page=2&_limit=2>; rel="next", <http://localhost:3000/blogs?_page=2&_limit=2>; rel="last"

添加排序和顺序(默认为升序)

GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc

Slice 截取,从已有的数组中返回选定的元素。通过 _start_end 或者 _limit 处理请求。

GET /posts?_start=20&_end=30
GET /posts/1/comments?_start=20&_end=30
GET /posts/1/comments?_start=20&_limit=10

要在 JavaScript 中访问我们的服务器,我们将使用 fetch。这相当简单。

fetch("http://localhost:3000/blogs")
.then(response=>response.json())
.then(data=> console.log(data))

将数据 POST 到 json-server,我们只需要三个配置:method,headers,和 body。

这 method 是我们将要发出的请求类型,这将是 “POST”。headers 告诉 fetch 我们将与之交互的数据类型,对我们来说它将是 “Content-Type”:“application/json”。最后 body 是我们将要发布到服务器的数据。

const newBlog = {title:"Learning JavaScirpt", content:"I learned about objects today!", author:"Java"}

const fetchPostConfig = {
  method:"POST",
  headers:{
    "Content-Type": "application/json",
    "Accept": "appication/json"
  },
  body:JSON.stringify(newBlog)
}

fetch("http://localhost:3000/blogs", fetchPostConfig)
.then(response => response.json())
.then(data => console.log(data))

更多 API 功能可以参考官网:github.com/typicode/js…