json-serve服务

使用json-server可以指定一个json文件作为api数据源,托管为一个具备RESTful的分割的API,并支持跨域、jsonp、路由定制,数据快照保存等功能的web服务器

  1. 安装
npm i -g json-server // 全局安装
  1. 启动服务
# json-server [options] <source>
json-server --watch db.json
# 把db.json文件托管成一个web服务
  1. 相关参数
参数 简写 默认值 说明
--config -c 指定配置文件 [默认值: "json-server.json"]
--port -p 设置端口 [默认值: 3000] Number
--host -H 设置域 [默认值: "0.0.0.0"] String
--watch -w Watch file(s) 是否监听
--routes -r 指定自定义路由
--middlewares -m 指定中间件 files [数组]
--static -s Set static files directory 静态目录,类比:express的静态目录
--readonly --ro Allow only GET requests [布尔]
--nocors --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"]
--foreignKeySuffix -- fks Set foreign key suffix (e.g. _id as in post_id) [默认值: "Id"]
--help -h 显示帮助信息 [布尔]
--version -v 显示版本号 [布尔]

source可以是json文件或者js文件

json-serve --watch app.js
json-serve --watch db.json

请求格式

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

请求格式

http://localhost:3001/comments  # get请求

# 只能通过id过滤数据,只支持匹配第一层数据的id,拿到的是一个对象
http://localhost:3001/comments/1	# get请求
# 通过其他属性过滤,拿到的是一个数组
http://localhost:3001/comments?body=some comment

# delete
http://localhost:3001/comments   // 返回对象的接口,不进行删除
http://localhost:3001/comments/1 // 请求删除数组列表的一项,删除成功

定义路由

使用单独的route.json文件,进行自定义路由。(类似于代理转发,拦截请求,并重定向访问)

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

自定义配置文件

默认配置文件json-server.json

{
  "port": 53000,
  "watch": true,
  "static": "./public",
  "read-only": false,
  "no-cors": false,
  "no-gzip": false,
  "routes": "route.json"
}
# 指定配置文件
json-server --watch -c jserver.json db.json

过滤查询

过滤字段,只针对数组数据

_gte:大于等于

_lte:小于等于

_ne:不等于

_link:包含

例: http://localhost:3001/data1?age_gte=20&age_lte=30`

_page:访问第几页数据

_limit:一共多少条(默认一页10条)

_sort:设定排序字段

order:设定排序方式(升序:asc;降序:desc,默认升序)

例:http://localhost:3001/data1?_sort=age&_order=asc

_start:数据截取起始坐标

_end:数据截取终止坐标

_limit:截取数据条数

例:http://localhost:3001/data1?_start=0&_end=1

http://localhost:3001/data1?_start=0&_limit=2

mockjs

动态生成数据模拟,json-server --watch app.js

var Mock =require('mockjs')

module.exports = () =>{
  var data = Mock.mock({
    // 属性list的值是一个数组,其中含有到铬元素
    'list|1-10':[{
      // 属性di是一个自增数,起始值为1
      'id|+1': 1
    }]
  })
}

参照:https://www.cnblogs.com/fly_dragon/p/9150732.html

posted @ 2020-12-08 15:51  黑色外套  阅读(89)  评论(0)    收藏  举报