前端接口神器之 json-server 詳細使用指南


簡介

json-server 是一款小巧的接口模擬工具,一分鍾內就能搭建一套 Restful 風格的 API,尤其適合前端接口測試使用。🔥🔥🔥
只需指定一個 json 文件作為 api 的數據源即可,使用起來非常方便,30 秒入門,基本上有手就行。👍
進階操作還支持分頁,排序等操作,簡直強大。💪

開源地址

主頁地址:https://www.npmjs.com/package/json-server
Github項目地址:https://github.com/typicode/json-server

30秒入門

環境依賴

  • 安裝 Node.js 環境即可

操作步驟

  1. 安裝 JSON 服務器
npm install -g json-server
  1. 創建一個db.json包含一些數據的文件
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}
  1. 啟動 json-server 接口服務器
# 快速創建
json-server db.json

# 配置參數
json-server db.json --watch --port 3000
  1. 瀏覽器訪問 http://localhost:3000/posts/1,你會得到
{ "id": 1, "title": "json-server", "author": "typicode" }
  1. 🎉恭喜你,已經完成 json-server 快速搭建,熟練使用的話 30 秒即可完成服務器搭建⏰。

補充

  • 如果您發出 POST、PUT、PATCH 或 DELETE 請求,更改將自動安全地保存到 db.json 文件中。

路由進階

根據之前的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標題,你會得到firstprevnextlast鏈接。

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

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

提示:使用FakerCasualChanceJSON 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 服務器路由器。

總結

  1. json-server 入門簡單,30 秒出效果,零編碼實現 REST API 風格接口,實屬前端接口神器。👍👍👍
  2. 路由進階操作還支持分頁,排序等操作,簡直強大。💪
  3. 感謝點贊與支持💕💕💕


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM