接口神器之 Json Server 详细指南
简介
json-server 是一款小巧的接口模拟工具,一分钟内就能搭建一套 Restful 风格的 api,尤其适合前端接口测试使用。
只需指定一个 json 文件作为 api 的数据源即可,使用起来非常方便,基本上有手就行。
开源地址
主页地址:https://www.npmjs.com/package/json-server
Github项目地址:https://github.com/typicode/json-server
入门
环境依赖
- 安装 Node.js 环境即可
操作步骤
- 安装 JSON 服务器
npm install -g json-server
- 创建一个
db.json包含一些数据的文件
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
- 启动
json-server接口服务器
json-server --watch db.json
- 浏览器访问 http://localhost:3000/posts/1,你会得到
{ "id": 1, "title": "json-server", "author": "typicode" }
补充
- 如果您发出 POST、PUT、PATCH 或 DELETE 请求,更改将自动安全地保存到
db.json文件中。 - 注意 Id 值是不可变的。
路由
根据之前的db.json文件,这里是所有的默认路由。
路由形式一
GET /posts
GET /posts/1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1
路由形式二
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对返回的数据进行分页。
在Link标题,你会得到first,prev,next和last链接。
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
切片(分页)
添加_start和_end或_limit(X-Total-Count响应中包含标头
GET /posts?_start=20&_end=30
GET /posts/1/comments?_start=20&_end=30
GET /posts/1/comments?_start=20&_limit=10
与Array.slice完全一样工作(即_start具有包容性和_end排他性)
特殊符号
添加_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
关系
要包含子资源,请添加 _embed
GET /posts?_embed=comments
GET /posts/1?_embed=comments
要包含父资源,请添加 _expand
GET /comments?_expand=post
GET /comments/1?_expand=post
获取或创建嵌套资源(默认为一级)
GET /posts/1/comments
POST /posts/1/comments
数据库
GET /db
主页
返回默认索引文件或服务./public目录
GET /
附加功能
静态文件服务器
您可以使用 JSON Server 为您的 HTML、JS 和 CSS 提供服务,只需创建一个./public目录或用于--static设置不同的静态文件目录。
mkdir public
echo 'hello world' > public/index.html
json-server db.json
json-server db.json --static ./some-other-dir
替换端口
您可以使用以下--port标志在其他端口上启动 JSON Server :
$ json-server --watch db.json --port 3004
支持跨域
您可以使用 CORS 和 JSONP 从任何地方访问您模拟的 API 接口。
远程模式
您可以加载远程模式。
$ json-server http://example.com/file.json
$ json-server http://jsonplaceholder.typicode.com/db
生成随机数据
使用 JS 而不是 JSON 文件,您可以通过编程方式创建数据。
// index.js
module.exports = () => {
const data = { users: [] }
// 创建 1000 个用户信息
for (let i = 0; i < 1000; i++) {
data.users.push({ id: i, name: `user${i}` })
}
return data
}
$ json-server index.js
提示:使用Faker、Casual、Chance或JSON Schema Faker 等模块。
添加自定义路由
创建一个routes.json文件。注意每条路线都以/.
{
"/api/*": "/$1",
"/:resource/:id/show": "/:resource/:id",
"/posts/:category": "/posts?category=:category",
"/articles\\?id=:id": "/posts/:id"
}
使用--routes选项启动 JSON 服务器。
json-server db.json --routes routes.json
现在您可以使用其他路线访问资源。
/api/posts # → /posts
/api/posts/1 # → /posts/1
/posts/1/show # → /posts/1
/posts/javascript # → /posts?category=javascript
/articles?id=1 # → /posts/1
添加中间件
您可以使用以下--middlewares选项从 CLI 添加中间件:
// hello.js
module.exports = (req, res, next) => {
res.header('X-Hello', 'World')
next()
}
json-server db.json --middlewares ./hello.js
json-server db.json --middlewares ./first.js ./second.js
命令行使用
json-server [options] <source>
Options:
--config, -c Path to config file [default: "json-server.json"]
--port, -p Set port [default: 3000]
--host, -H Set host [default: "localhost"]
--watch, -w Watch file(s) [boolean]
--routes, -r Path to routes file
--middlewares, -m Paths to middleware files [array]
--static, -s Set static files directory
--read-only, --ro Allow only GET requests [boolean]
--no-cors, --nc Disable Cross-Origin Resource Sharing [boolean]
--no-gzip, --ng Disable GZIP Content-Encoding [boolean]
--snapshots, -S Set snapshots directory [default: "."]
--delay, -d Add delay to responses (ms)
--id, -i Set database id property (e.g. _id) [default: "id"]
--foreignKeySuffix, --fks Set foreign key suffix, (e.g. _id as in post_id)
[default: "Id"]
--quiet, -q Suppress log messages from output [boolean]
--help, -h Show help [boolean]
--version, -v Show version number [boolean]
Examples:
json-server db.json
json-server file.js
json-server http://example.com/db.json
https://github.com/typicode/json-server
您还可以在json-server.json配置文件中设置选项。
{
"port": 3000
}
模块
如果您需要添加身份验证、验证或任何行为,您可以将项目作为模块与其他 Express 中间件结合使用。
简单的例子
$ npm install json-server --save-dev
// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
$ node server.js
您提供给jsonServer.router函数的路径是相对于您启动节点进程的目录的。如果从另一个目录运行上述代码,最好使用绝对路径:
const path = require('path')
const router = jsonServer.router(path.join(__dirname, 'db.json'))
对于内存数据库,只需将对象传递给jsonServer.router().
另请注意,jsonServer.router()它可用于现有的 Express 项目。
自定义路由示例
假设您想要一个回显查询参数的路由和另一个在创建的每个资源上设置时间戳的路由。
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
// 设置默认中间件(记录器、静态、cors 和无缓存)
server.use(middlewares)
// 写在自定义路由之前
server.get('/echo', (req, res) => {
res.jsonp(req.query)
})
// 要处理 POST、PUT 和 PATCH,您需要使用 body-parser
// 您可以使用 JSON Server
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
if (req.method === 'POST') {
req.body.createdAt = Date.now()
}
// 继续到 JSON Server 路由器
next()
})
// 使用默认路由器
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)) { // 在此处添加您的授权逻辑
next() // 继续到 JSON Server 路由器
} else {
res.sendStatus(401)
}
})
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
自定义输出示例
要修改响应,请覆盖router.render方法:
// 在这个例子中,返回的资源将被包装在一个 body 属性
router.render = (req, res) => {
res.jsonp({
body: res.locals.data
})
}
您可以为响应设置自己的状态代码:
// 在这个例子中,我们模拟了一个服务器端错误响应
router.render = (req, res) => {
res.status(500).jsonp({
error: "error message here"
})
}
重写器示例
要添加重写规则,请使用jsonServer.rewriter():
// 写在 server.use(router) 之前
server.use(jsonServer.rewriter({
'/api/*': '/$1',
'/blog/:resource/:id/show': '/:resource/:id'
}))
在另一个端点上挂载 JSON 服务器示例
或者,您也可以将路由器安装在/api.
server.use('/api', router)
API
jsonServer.create()
返回一个 Express 服务器。
jsonServer.defaults([options])
返回 JSON 服务器使用的中间件。
- 选项
static静态文件的路径logger启用记录器中间件(默认值:true)bodyParser启用 body-parser 中间件(默认值:true)noCors禁用 CORS(默认值:false)readOnly只接受 GET 请求(默认值:false)
jsonServer.router([path|object])
返回 JSON 服务器路由器。
接口神器之 Json Server 详细指南的更多相关文章
- 三小时学会Kubernetes:容器编排详细指南
三小时学会Kubernetes:容器编排详细指南 如果谁都可以在三个小时内学会Kubernetes,银行为何要为这么简单的东西付一大笔钱? 如果你心存疑虑,我建议你不妨跟着我试一试!在完成本文的学习后 ...
- ORACLE恢复神器之ODU/AUL/DUL
分享ORACLE数据库恢复神器之ODU.DUL和AUL工具. ODU:ORACLE DATABASE UNLOADER DUL:DATA UNLOADER AUL:也称MyDUL 关于三种工具说明: ...
- 『动善时』JMeter基础 — 35、JMeter接口关联【JSON提取器】详解
目录 1.JSON提取器介绍 2.JSON提取器界面详解 3.JSON提取器的使用 (1)测试计划内包含的元件 (2)HTTP Cookie管理器内容 (3)用户登陆请求界面内容 (4)JSON提取器 ...
- 常用的API接口,返回JSON格式的服务API接口
物流接口 快递接口: http://www.kuaidi100.com/query?type=快递公司代号&postid=快递单号 ps:快递公司编码:申通="shentong&qu ...
- 如何让Java和C++接口互相调用:JNI使用指南
如何让Java和C++接口互相调用:JNI使用指南 转自:http://cn.cocos2d-x.org/article/index?type=cocos2d-x&url=/doc/cocos ...
- 用javascript向一个网页连接接口发送请求,并接收该接口返回的json串
一般前端与后端的互交都是通过json字符串来互交的,我的理解就是与网页接口的来回数据传递采用的数据结构就是json.一般是这样. 比如后端的代码是这样的: @RequestMapping(value ...
- 关于http接口开发中json格式数据编码问题处理
关于http接口开发中json格式数据编码问题处理 在实际工作中,接口很多时候返回json格式,但有时返回的格式会有编码问题 假设如下接口:http://service.test.com/interf ...
- json server服务器
json文件可以理解为数据库 一.json-server快速搭建RESTAPI 安装: sudo cnpm install -g json-server 启动(使用): json-server指向js ...
- json server的简单使用(附:使用nodejs快速搭建本地服务器)
作为前端开发人员,经常需要模拟后台数据,我们称之为mock.通常的方式为自己搭建一个服务器,返回我们想要的数据.json server 作为工具,因为它足够简单,写少量数据,即可使用. 安装 首先需要 ...
随机推荐
- mit6.830-lab2-常见算子和 volcano 执行模型
一.实验概览 github : https://github.com/CreatorsStack/CreatorDB 这个实验需要完成的内容有: 实现过滤.连接运算符,这些类都是继承与OpIterat ...
- 替换资源(Project)
<Project2016 企业项目管理实践>张会斌 董方好 编著 还是那个熟悉的某吃货甲,一天之内给他分配了9.6个工时的吃量,这太不厚道了哈,人家一个人又要开吃又要喝汤,这怎么吃得消呢? ...
- HMS Core版本发布公告
新增动作捕捉能力.通过简单拍摄即可获得人体3D骨骼关键点数据,广泛应用于虚拟形象.体育运动和医学分析等场景: 3D物体建模能力iOS版本上线. 查看详情>> 新增道路吸附能力.可根据坐标点 ...
- android jni-dlerror报undefined symbol: JNI_OnLoad
以下是很简单的一个官方的jni方法,在MainActivity的onCreate中调用 extern "C" JNIEXPORT jstring JNICALL Java_com_ ...
- CF706A Beru-taxi 题解
Content 有一个人在点 \((a,b)\) 等出租车.已知他周围共有 \(n\) 辆出租车,其中第 \(i\) 辆车在点 \((x_i,y_i)\) 上,速度为 \(v_i\).这个人想打能让他 ...
- Unhandled Exception: FormatException: Unexpected character
错误原因 json格式不正确,检查:是否加了注释.最后一个是否加了逗号... 正确格式 { "name": "shellon", "age" ...
- wayne编译支持k8s1.16+
GitHub: https://github.com/Qihoo360/wayne 文档: 由于wayne 官方文档链接已经失效了,我们可以通过这里查看 wayne 文档, 除了这个地方,我们询问之前 ...
- java类型转换拓展
数据类型拓展 在Java中二进制用0b开头,八进制用0开头,十六进制用0x表示 整数拓展 int i=10; int i2=010;//八进制 int i3=0x10;//十六进制0x,0-9,A- ...
- 再谈多线程模型之生产者消费者(多生产者和单一消费者 )(c++11实现)
0.关于 为缩短篇幅,本系列记录如下: 再谈多线程模型之生产者消费者(基础概念)(c++11实现) 再谈多线程模型之生产者消费者(单一生产者和单一消费者)(c++11实现) 再谈多线程模型之生产者消费 ...
- 【LeetCode】940. Distinct Subsequences II 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址:https://leetc ...