前端插件json-server快速实现 一个本地的mock-server

作为一个前端开发工程师,在后端还没有ready的时候,不可避免的要使用mock的数据。很多时候,我们并不想使用简单的静
态数据,而是希望自己起一个本地的mock-server来完全模拟请求以及请求回来的过程。json-server是一个很好的可以替我们完
成这一工作的工具。我们只需要提供一个json文件,或者写几行简单的js脚本就可以模拟出RESTful API的接口。

官方文档: https://github.com/typicode/json-server

1.使用

1.安装

npm install -g json-server

2.创建 db.json

{
	"users":[
		{
			"name" : "张三",
			"age":30,
			"score":89
		},
		{
			"name":"李四",
			"age":43,
			"score":89
		},
		{
			"name":"王五",
			"age":34,
			"score":89
		}
	]
}

3.启动服务
例如以下命令,把db.json文件托管成一个 web 服务。

$ json-server --watch --port 53000 db.json

输出类似以下内容,说明启动成功。

> json-server --watch --port 8900 db.json

 \{^_^}/ hi!

 Loading db.json
 Done

 Resources
 http://localhost:8900/users

 Home
 http://localhost:8900

 Type s + enter at any time to create a snapshot of the database
 Watching...

GET /users 200 13.595 ms - 188

我们用浏览器访问 : http://localhost:8900/users
在这里插入图片描述
也可以使用js文件 代替json文件

// index.js
module.exports = () => {
  const data = { users: [] }
  // Create 1000 users
  for (let i = 0; i < 1000; i++) {
    data.users.push({ id: i, name: `user${i}` })
  }
  return data
}
$ json-server index.js

2. 路由

创建一个路由json ,routes.js

{
  "/api/*": "/$1",
  "/:resource/:id/show": "/:resource/:id",
  "/posts/:category": "/posts?category=:category",
  "/articles\\?id=:id": "/posts/:id"
}

db.json

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

使用 --routes 选项进行启动

json-server db.json --routes routes.json
> json-server db.json --routes routes.json

  \{^_^}/ hi!

  Loading db.json
  Oops, db.json doesn't seem to exist
  Creating db.json with some default data

  Loading routes.json
  Done

  Resources
  http://localhost:3000/posts
  http://localhost:3000/comments
  http://localhost:3000/profile

  Other routes
  /api/* -> /$1
  /:resource/:id/show -> /:resource/:id
  /posts/:category -> /posts?category=:category
  /articles\?id=:id -> /posts/:id

  Home
  http://localhost:3000

我们可以访问以下路由:

http://localhost:3000/api/posts
http://localhost:3000/api/posts/1
http://localhost:3000/posts/1/show

其他路由:

3.条件查询

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

分页
使用_page(第几页) 和 _limit(每页多少条) 去分页

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

默认每页10条

排序
使用_sort 和 _order 关键字去排序

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

多个字段进行排序

GET /posts?_sort=user,views&_order=desc,asc

其他操作

  • _gte 大于等于
  • _lte 小于等于
GET /posts?views_gte=10&views_lte=20
  • _ne 不等于
GET /posts?id_ne=1
  • _like 包含
GET /posts?title_like=server
  • q 全文检索
GET /posts?q=internet

4. --middlewares参数

// hello.js
module.exports = (req, res, next) => {
  res.header('X-Hello', 'World')
  next()
}

上面代码是 给响应头添加自定义字段:

在这里插入图片描述

5. json-server 的相关启动参数

语法: json-server [options]

参数简写说明默认值
–config-c配置文件路径[默认值: “json-server.json”]
–port-p设置端口[默认值: 3000]
–host-H设置域名[默认: “localhost”]
–watch-w监控文件[true]
–routes-r路由文件
–middlewares-m中间文件[array]
–static-sSet static files directory
–read-only–roAllow only GET requests[boolean]
–no-cors–ncDisable Cross-Origin Resource Sharing[boolean]
–no-gzip–ngDisable GZIP Content-Encoding[boolean]
–snapshots-SSet snapshots directory[default: “.”]
–delay-dAdd delay to responses
–id-iSet database id property (e.g. _id)[default: “id”]
–foreignKeySuffix–fksSet foreign key suffix, (e.g. _id as in post_id)[default: “Id”]
–quiet-qSuppress log messages from output[boolean]
–help-hShow help[boolean]
–version-vShow version number[boolean]

实例:
文件可以是JSON 或者jS 文件

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

6.高级用法

我们可以使用编程,来实现高级用法

1.自定义路由

当你路由的时候,如果是POST方式,则需要在body带上当前时间,实现代码如下:

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares)

// Add custom routes before JSON Server router
server.get('/echo', (req, res) => {
  res.jsonp(req.query)
})

// To handle POST, PUT and PATCH you need to use a body-parser
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
  if (req.method === 'POST') {
    req.body.createdAt = Date.now()
  }
  // Continue to JSON Server router
  next()
})

// Use default router
server.use(router)
server.listen(3000, () => {
  console.log('JSON Server is running')
})

资源授权例子

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

server.use(middlewares)
server.use((req, res, next) => {
 if (isAuthorized(req)) { // add your authorization logic here
   next() // continue to JSON Server router
 } else {
   res.sendStatus(401)
 }
})
server.use(router)
server.listen(3000, () => {
  console.log('JSON Server is running')
})

自定义输出内容

// In this example, returned resources will be wrapped in a body property
router.render = (req, res) => {
  res.jsonp({
    body: res.locals.data
  })
}

你可以定义自己的响应code

// In this example we simulate a server side error response
router.render = (req, res) => {
  res.status(500).jsonp({
    error: "error message here"
  })
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半夏_2021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值