json-server-node
support multiply files config 基于node启动的json-server的mock系统,启动后自动读取指定目录dbs中的json文件,node版本v10LTS
git地址: github.com/ShadowWalke…
git clone后直接执行
npm start
通过nodemon启动服务,可监控dbs文件夹中的任一未被忽略的目录下的json文件的变化,支持自动重启服务
服务启动后会自动列出现有的可用API,可通过设置db.js中的excludes中的文件夹列表,忽略掉某些文件夹中的json文件
// db.js
const excludes = ['demo']; // 要忽略的文件夹
const allDBFiles = readAllFilesInFolder('./dbs/', excludes);
默认端口4000
启动示例:
------JSON Server is running: 4000-------
http://localhost:4000/posts
http://localhost:4000/comments
http://localhost:4000/profile
http://localhost:4000/getUserProfit
http://localhost:4000/shapeDetail
应用场景:
- 开发过程中后端已经提供接口文档但未提供可用接口API调用时,便于前端mock接口
- 后期维护过程中,线上环境有数据,但是本地环境不便直接获取线上环境时,mock接口使用
工具优势在于不用关心json-server相关的启动与配置,只需要在指定目录下放置接口数据的json文件即可,支持多文件
json-server [options] <source>
Options:
--config, -c 指定 config 文件 [默认: "json-server.json"]
--port, -p 设置端口号 [default: 3000]
--host, -H 设置主机 [默认: "0.0.0.0"]
--watch, -w 监控文件 [boolean]
--routes, -r 指定路由文件
--static, -s 设置静态文件
--read-only, --ro 只允许 GET 请求 [boolean]
--no-cors, --nc 禁止跨域资源共享 [boolean]
--no-gzip, --ng 禁止GZIP [boolean]
--snapshots, -S 设置快照目录 [默认: "."]
--delay, -d 设置反馈延时 (ms)
--id, -i 设置数据的id属性 (e.g. _id) [默认: "id"]
--quiet, -q 不输出日志信息 [boolean]
--help, -h 显示帮助信息 [boolean]
--version, -v 显示版本号 [boolean]
Examples:
bin db.json
bin file.js
bin http://example.com/db.json
1、最简单用法
创建一个db.json文件
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
启动服务
json-server --watch db.json
默认启动端口:3000,启动后访问 http://localhost:3000/posts/1,返回
{ "id": 1, "title": "json-server", "author": "typicode" }
可以支持:筛选、排序、分页、切片等操作,也可作为静态文件服务器,其中静态文件就是在根目录中建立一个public文件夹,服务启动后即可直接文件夹内的文件,例如:http://localhost:4000/classicalShape.json。也可以在启动服务时对静态文件所在目录进行声明:
json-server db.json --static ./some-other-dir
欢迎扫码关注作者公众号
