基於node啓動的json-server的mock API服務,啓動後自動讀取指定目錄中多個json文件,node版本v10LTS

json-server-node

support multiply files config
基於node啓動的json-server的mock系統,啓動後自動讀取指定目錄dbs中的json文件,node版本v10LTS

git地址:
https://github.com/ShadowWalker627/json-server-node

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 

應用場景:

  1. 開發過程中後端已經提供接口文檔但未提供可用接口API調用時,便於前端mock接口
  2. 後期維護過程中,線上環境有數據,但是本地環境不便直接獲取線上環境時,mock接口使用

工具優勢在於不用關心json-server相關的啓動與配置,只需要在指定目錄下放置接口數據的json文件即可,支持多文件

json-server git地址

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

歡迎掃碼關注作者公衆號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章