JSON-Server 是一个 Node 模块,运行 Express 服务器,你可以指定一个 json 文件作为 api 的数据源。

安装json-server

npm install -g json-server

启动 json-server

json-server可以直接把一个json文件托管成一个具备全RESTful风格的API,并支持跨域、jsonp、路由订制、数据快照保存等功能的 web 服务器。

db.json文件的内容:

{
"course": [
{
"id": 1000,
"course_name": "马连白米且",
"autor": "袁明",
"college": "金并即总变史",
"category_Id": 2
},
{
"id": 1001,
"course_name": "公拉农题队始果动",
"autor": "高丽",
"college": "先了队叫及便",
"category_Id": 2
}
}
}

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

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

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

\{^_^}/ hi!

Loading db.json
Done Resources
http://localhost:53000/course Home
http://localhost:53000 Type s + enter at any time to create a snapshot of the database
Watching...

此时,你可以打开你的浏览器,然后输入:http://localhost:53000/course

json-server 的相关启动参数

  • 语法:json-server [options] <source>

  • 选项列表:

参数 简写 默认值 说明
--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-server --watch -c ./jsonserver.json
$ json-server --watch app.js
$ json-server db.json
json-server --watch -port 8888 db.json

动态生成模拟数据

例如启动json-server的命令:json-server --watch app.js 是把一个js文件返回的数据托管成web服务。

app.js配合mockjs库可以很方便的进行生成模拟数据。

// 用mockjs模拟生成数据
var Mock = require('mockjs'); module.exports = () => {
// 使用 Mock
var data = Mock.mock({
'course|227': [
{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|+1': 1000,
course_name: '@ctitle(5,10)',
autor: '@cname',
college: '@ctitle(6)',
'category_Id|1-6': 1
}
],
'course_category|6': [
{
"id|+1": 1,
"pid": -1,
cName: '@ctitle(4)'
}
]
});
// 返回的data会作为json-server的数据
return data;
};

路由

默认的路由

json-server为提供了GET,POSTPUTPATCH ,DELETE等请求的API,分别对应数据中的所有类型的实体。

# 获取所有的课程信息
GET /course # 获取id=1001的课程信息
GET /course/1001 # 添加课程信息,请求body中必须包含course的属性数据,json-server自动保存。
POST /course # 修改课程,请求body中必须包含course的属性数据
PUT /course/1
PATCH /course/1 # 删除课程信息
DELETE /course/1 # 获取具体课程信息id=1001
GET /course/1001

自定义路由

当然你可以自定义路由:

$ json-server --watch --routes route.json db.json

route.json文件

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

自定义配置文件

通过命令行配置路由、数据文件、监控等会让命令变的很长,而且容易敲错,可以把命令写到npm的scripts中,但是依然配置不方便。

json-server允许我们把所有的配置放到一个配置文件中,这个配置文件默认json-server.json;

例如:

{
"port": 53000,
"watch": true,
"static": "./public",
"read-only": false,
"no-cors": false,
"no-gzip": false,
"routes": "route.json"
}

使用配置文件启动json-server:

# 默认使用:json-server.json配置文件
$ json-server --watch app.js # 指定配置文件
$ json-server --watch -c jserver.json db.json

过滤查询

查询数据,可以额外提供

GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2 # 可以用 . 访问更深层的属性。
GET /comments?author.name=typicode

还可以使用一些判断条件作为过滤查询的辅助。

GET /posts?views_gte=10&views_lte=20

可以用的拼接条件为:

  • _gte : 大于等于
  • _lte : 小于等于
  • _ne : 不等于
  • _like : 包含
GET /posts?id_ne=1
GET /posts?id_lte=100
GET /posts?title_like=server

分页查询

默认后台处理分页参数为: _page 第几页, _limit一页多少条。

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

默认一页10条。

后台会返回总条数,总条数的数据在响应头:X-Total-Count中。

排序

  • 参数: _sort设定排序的字段
  • 参数: _order设定排序的方式(默认升序)
GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc

支持多个字段排序:

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

任意切片数据

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

全文检索

可以通过q参数进行全文检索,例如:GET /posts?q=internet

实体关联

关联子实体

包含children的对象, 添加_embed

GET /posts?_embed=comments
GET /posts/1?_embed=comments

关联父实体

包含 parent 的对象, 添加_expand

GET /comments?_expand=post
GET /comments/1?_expand=post

其他高级用法

json-server本身就是依赖express开发而来,可以进行深度定制。细节就不展开,具体详情请参考官网

  • 自定义路由
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults() server.use(middlewares) server.get('/echo', (req, res) => {
res.jsonp(req.query)
}) server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
if (req.method === 'POST') {
req.body.createdAt = Date.now()
}
next()
}) server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
  • 自定义输出内容
router.render = (req, res) => {
res.jsonp({
body: res.locals.data
})
}
  • 自定义用户校验
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')
})

json-server 详解的更多相关文章

  1. Angular 6.X CLI(Angular.json) 属性详解

    Angular CLI(Angular.json) 属性详解 简介 angular cli 是angular commond line interface的缩写,意为angular的命令行接口.在an ...

  2. Angular Npm Package.Json文件详解

    Angular7 Npm Package.Json文件详解   近期时间比较充裕,正好想了解下Angular Project相关内容.于是将Npm官网上关于Package.json的官方说明文档进行了 ...

  3. SpringMVC接受JSON参数详解及常见错误总结我改

    SpringMVC接受JSON参数详解及常见错误总结 最近一段时间不想使用Session了,想感受一下Token这样比较安全,稳健的方式,顺便写一个统一的接口给浏览器还有APP.所以把一个练手项目的前 ...

  4. 转:Parameter Server 详解

    Parameter Server 详解   本博客仅为作者记录笔记之用,不免有很多细节不对之处. 还望各位看官能够见谅,欢迎批评指正. 更多相关博客请猛戳:http://blog.csdn.net/c ...

  5. SpringMVC接受JSON参数详解及常见错误总结

    SpringMVC接受JSON参数详解及常见错误总结 SpringMVC接受JSON参数详解及常见错误总结 最近一段时间不想使用Session了,想感受一下Token这样比较安全,稳健的方式,顺便写一 ...

  6. SpringMVC接受JSON参数详解

    转:https://blog.csdn.net/LostSh/article/details/68923874 SpringMVC接受JSON参数详解及常见错误总结 最近一段时间不想使用Session ...

  7. 最强常用开发库总结 - JSON库详解

    最强常用开发库总结 - JSON库详解 JSON应用非常广泛,对于Java常用的JSON库要完全掌握.@pdai JSON简介 JSON是什么 JSON 指的是 JavaScript 对象表示法(Ja ...

  8. spring-mvc注解(mvc:annotation-driver,JSON,配置详解)

    一.DefaultAnnotationHandlerMapping 和 AnnotationMethodHandlerAdapter 的使用已经过时! spring 3.1 开始我们应该用 Reque ...

  9. android Json解析详解

    JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语 言的支持),从而可以在不同平台间进行数 ...

  10. android Json解析详解(详细代码)

    JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...

随机推荐

  1. POJ 2752 (kmp求所有公共前后缀长度)

    <题目链接> <转载于> 题目大意:  给出一个字符串str,求出str中存在多少子串,使得这些子串既是str的前缀,又是str的后缀.从小到大依次输出这些子串的长度.即输出该 ...

  2. 阿里云服务器配置免费https服务

    过程总述 购买服务器,购买域名,备案 申请ssl证书 DNS验证 上传证书,配置nginx 很关键,打开端口!!!阿里云的443端口默认是不打开的 1.购买服务器,域名,备案 服务器我是买的阿里云的, ...

  3. python 常用模块之random,os,sys 模块

    python 常用模块random,os,sys 模块 python全栈开发OS模块,Random模块,sys模块 OS模块 os模块是与操作系统交互的一个接口,常见的函数以及用法见一下代码: #OS ...

  4. Orleans部署

    一.配置指南 1,客户端配置 2,服务端配置 3,典型配置 4,配置.NET垃圾收集 5,SQL系统存储 二.监控 1,运行时监视 2,silo错误代码监测 3,客户端错误代码监测 三.解决部署问题 ...

  5. 如何开发一个npm包并发布

    一.安装nodejs 不多说了,网上教程多得是 二.创建自己的npm包 目录结构 npm-test a.js b.js package.json 开发 为了简单便于理解,就开发一个简单地hello程序 ...

  6. DataGridView 使用精华

    DataGridView控件用法合集 1. 当前的单元格属性取得.变更 [C#] //显示当前单元格的值 Console.WriteLine(DataGridView1.CurrentCell.Val ...

  7. 洛谷.3809.[模板]后缀排序(后缀数组 倍增) & 学习笔记

    题目链接 //输出ht见UOJ.35 #include<cstdio> #include<cstring> #include<algorithm> const in ...

  8. Django-自定义增删改查组件的一些体会

    1.路由系统 namespace,用于区分相同name的url,通过namespace为url添加一个前缀 反向生成URL的时候 reverse('namespace:name') {% url &q ...

  9. node+koa2 使用ejs模版

    1.进入项目下,npm install -save ejs 2.app.js加入: const ejs = require('ejs'); app.use(views(__dirname + '/vi ...

  10. Content-type详解

    HttpHeader里的Content-Type 之前一直分不清楚post请求里Content-Type方式,如application/x-www-form-urlencoded.multipart/ ...