一分鐘內(nèi)搭建全web的API接口神器json-server詳解

json-server 詳解

JSON-Server 是一個(gè) Node 模塊,運(yùn)行 Express 服務(wù)器,你可以指定一個(gè) json 文件作為 api 的數(shù)據(jù)源。

安裝json-server

npm install -g json-server

啟動(dòng) json-server

json-server可以直接把一個(gè)json文件托管成一個(gè)具備全RESTful風(fēng)格的API,并支持跨域、jsonp、路由訂制、數(shù)據(jù)快照保存等功能的 web 服務(wù)器。

db.json文件的內(nèi)容:

{
  "course": [
    {
      "id": 1000,
      "course_name": "馬連白米且",
      "autor": "袁明",
      "college": "金并即總變史",
      "category_Id": 2
    },
    {
      "id": 1001,
      "course_name": "公拉農(nóng)題隊(duì)始果動(dòng)",
      "autor": "高麗",
      "college": "先了隊(duì)叫及便",
      "category_Id": 2
    }
  }
}

例如以下命令,把db.json文件托管成一個(gè) web 服務(wù)。

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

輸出類似以下內(nèi)容,說(shuō)明啟動(dòng)成功。

\{^_^}/ 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...

此時(shí),你可以打開你的瀏覽器,然后輸入:http://localhost:53000/course

json-server 的相關(guān)啟動(dòng)參數(shù)

  • 語(yǔ)法:json-server [options] <source>

  • 選項(xiàng)列表:

參數(shù) 簡(jiǎn)寫 默認(rèn)值 說(shuō)明
--config -c 指定配置文件 [默認(rèn)值: "json-server.json"]
--port -p 設(shè)置端口 [默認(rèn)值: 3000] Number
--host -H 設(shè)置域 [默認(rèn)值: "0.0.0.0"] String
--watch -w Watch file(s) 是否監(jiān)聽
--routes -r 指定自定義路由
--middlewares -m 指定中間件 files [數(shù)組]
--static -s Set static files directory 靜態(tài)目錄,類比:express的靜態(tài)目錄
--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 [默認(rèn)值: "."]
--delay -d Add delay to responses (ms)
--id -i Set database id property (e.g. _id) [默認(rèn)值: "id"]
--foreignKeySuffix -- fks Set foreign key suffix (e.g. _id as in post_id) [默認(rèn)值: "Id"]
--help -h 顯示幫助信息 [布爾]
--version -v 顯示版本號(hào) [布爾]
  • source可以是json文件或者js文件。實(shí)例:
$ json-server --watch -c ./jsonserver.json
$ json-server --watch app.js
$ json-server db.json
json-server --watch -port 8888 db.json

動(dòng)態(tài)生成模擬數(shù)據(jù)

例如啟動(dòng)json-server的命令:json-server --watch app.js 是把一個(gè)js文件返回的數(shù)據(jù)托管成web服務(wù)。

app.js配合mockjs庫(kù)可以很方便的進(jìn)行生成模擬數(shù)據(jù)。

// 用mockjs模擬生成數(shù)據(jù)
var Mock = require('mockjs');

module.exports = () => {
  // 使用 Mock
  var data = Mock.mock({
    'course|227': [
      {
        // 屬性 id 是一個(gè)自增數(shù),起始值為 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會(huì)作為json-server的數(shù)據(jù)
  return data;
};

路由

默認(rèn)的路由

json-server為提供了GET,POST, PUT, PATCH ,DELETE等請(qǐng)求的API,分別對(duì)應(yīng)數(shù)據(jù)中的所有類型的實(shí)體。

# 獲取所有的課程信息
GET    /course

# 獲取id=1001的課程信息
GET    /course/1001

# 添加課程信息,請(qǐng)求body中必須包含course的屬性數(shù)據(jù),json-server自動(dòng)保存。
POST   /course

# 修改課程,請(qǐng)求body中必須包含course的屬性數(shù)據(jù)
PUT    /course/1
PATCH  /course/1

# 刪除課程信息
DELETE /course/1

# 獲取具體課程信息id=1001
GET    /course/1001

自定義路由

當(dāng)然你可以自定義路由

$ 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"
}

自定義配置文件

通過(guò)命令行配置路由、數(shù)據(jù)文件、監(jiān)控等會(huì)讓命令變的很長(zhǎng),而且容易敲錯(cuò),可以把命令寫到npm的scripts中,但是依然配置不方便。

json-server允許我們把所有的配置放到一個(gè)配置文件中,這個(gè)配置文件默認(rèn)json-server.json;

例如:

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

使用配置文件啟動(dòng)json-server:

# 默認(rèn)使用:json-server.json配置文件
$ json-server --watch app.js  

# 指定配置文件
$ json-server --watch -c jserver.json db.json

過(guò)濾查詢

查詢數(shù)據(jù),可以額外提供

GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2

# 可以用 . 訪問(wèn)更深層的屬性。
GET /comments?author.name=typicode

還可以使用一些判斷條件作為過(guò)濾查詢的輔助。

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

分頁(yè)查詢

默認(rèn)后臺(tái)處理分頁(yè)參數(shù)為: _page 第幾頁(yè), _limit一頁(yè)多少條。

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

默認(rèn)一頁(yè)10條。

后臺(tái)會(huì)返回總條數(shù),總條數(shù)的數(shù)據(jù)在響應(yīng)頭:X-Total-Count中。

排序

  • 參數(shù): _sort設(shè)定排序的字段
  • 參數(shù): _order設(shè)定排序的方式(默認(rèn)升序)
GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc

支持多個(gè)字段排序:

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

任意切片數(shù)據(jù)

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

全文檢索

可以通過(guò)q參數(shù)進(jìn)行全文檢索,例如:GET /posts?q=internet

實(shí)體關(guān)聯(lián)

關(guān)聯(lián)子實(shí)體

包含children的對(duì)象, 添加_embed

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

關(guān)聯(lián)父實(shí)體

包含 parent 的對(duì)象, 添加_expand

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

其他高級(jí)用法

json-server本身就是依賴express開發(fā)而來(lái),可以進(jìn)行深度定制。細(xì)節(jié)就不展開,具體詳情請(qǐng)參考官網(wǎng)。

  • 自定義路由
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')
})
  • 自定義輸出內(nèi)容
router.render = (req, res) => {
  res.jsonp({
    body: res.locals.data
  })
}
  • 自定義用戶校驗(yàn)
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')
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,680評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,283評(píng)論 6 342
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,966評(píng)論 1 92
  • 常常聽人說(shuō),誰(shuí)誰(shuí)開小吃店又掙了多少錢,誰(shuí)誰(shuí)賣燒烤,又買房了,這些做小吃的,真有這么好賺么? 真相就是如此,掙的都是...
    溫暖的鏡子閱讀 782評(píng)論 0 0
  • 奇葩大會(huì)第二季來(lái)了人間世2的年輕導(dǎo)演。嘉賓問(wèn)他人間世這部紀(jì)錄片的名字是誰(shuí)起的?他說(shuō),是他們領(lǐng)導(dǎo)起的,領(lǐng)導(dǎo)有文化,有...
    神奇魔刀小姐姐閱讀 127評(píng)論 0 0

友情鏈接更多精彩內(nèi)容