1. 程式人生 > >一分鐘內搭建全web的API接口神器json-server詳解

一分鐘內搭建全web的API接口神器json-server詳解

一個 設置 director sha sna 用法 依然 ref 參考

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": "馬連白米且",
      "author": "袁明",
      "college": "金並即總變史",
      "category_Id": 2
    },
    {
      "id": 1001,
      "course_name": "公拉農題隊始果動",
      "author": "高麗",
      "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 [布爾]
--no-cors --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)‘,
        author: ‘@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,POST, PUT, PATCH ,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)

// 給post的請求返回創建時間的屬性
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
  })
}
  • 代碼控制添加自定義路由

重定向url地址,可以用jsonServer.rewriter()

server.use(jsonServer.rewriter({
  ‘/api/*‘: ‘/$1‘,
  ‘/blog/:resource/:id/show‘: ‘/:resource/:id‘
}))

另外可以把整個路由掛載到另外一個地址:

server.use(‘/api‘, router)
  • 自定義用戶校驗
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) => {
  // isAuthorized就是你自己校驗的邏輯
 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‘)
})

一分鐘內搭建全web的API接口神器json-server詳解