前言
Ajax 是前端必學的一個知識點,但剛接觸 Ajax 的同學可能會因為沒接口測試而煩惱。
本文 入門篇 會花你10分鐘解決 沒接口測試 這個煩惱,而且不需要你具備後端知識。
如果不想自己在本地搭環境,還可以使用 《前端需要的免費線上api接口》 裡推薦的幾個線上接口平台,裡面包括常用的 json 結構資料和圖檔。
雖然有線上的免費接口可以測試,但需要自定義接口和資料的時候,還是本地模拟資料比較适合前端開發者。
本文分 入門篇 和 進階篇。再往下滑一點就能看到全文目錄。
入門篇: 5分鐘内帶你實作 本地環境搭建 和 增删改查 操作,滿足入門測試使用。
進階篇: 主要講解常用的 查詢操作,除此之外還包括 正常配置、靜态資源配置 等知識點。這部分有點長,建議收藏。
本文約定
- 本文主要面向的讀者是 前端小白,幾乎不會涉及到後端知識,是以并不打算講解 json-server 中間件 的内容。
- 本文講到的所有知識點都會提供對應的代碼展示(會比官方文檔詳細點)。
- 本文使用 postman 測試,希望能照顧到使用不同工具庫做資料請求的讀者(我知道還有隻懂 jQuery 的開發者)。
- 特殊情況會使用 axios 配合示範。
點贊 + 收藏 = 學會了
目錄
入門
json-server簡介
npm位址:https://www.npmjs.com/package/json-server
github位址:https://github.com/typicode/json-server
Get a full fake REST API with zero coding in less than 30 seconds (seriously)
引用了官方的一句話,大概意思是30秒就能獲得一套完整的模拟 REST API 接口。
使用 json-server 需要遵守一定的規範。
- 資料查詢要使用 GET。
- 新增資料要使用 POST。
- 删除資料要使用 DELETE。
- 修改資料使用 PUT 和 PATCH。
其他啰嗦的介紹可以打開上面提供的網址看看。
30秒起步
30秒起步分 4 步完成:
- node 環境安裝
- 安裝 json-server
- 建立資料庫(其實就是一個 json 檔案)
- 啟動服務
1. node 環境安裝
json-server 需要通過 npm 下載下傳,npm 依賴在 node 中。
node 常見的安裝方法有2種。第一種是官方下載下傳,第二種是使用 nvm 下載下傳。自己選一種就行。
node 官網,點選進入首頁下載下傳,下載下傳完狂按“下一步”和“完成”就行了。
注意: node 版本一定要 12 以上。不然會報以下錯誤:
json-server requires at least version 12 of Node, please upgrade
2. 安裝 json-server
可以全局安裝,也可以在某項目裡安裝。這裡建議全局安裝,因為以後你可能會對 json-server 産生依賴。
全局安裝方式:
npm install -g json-server
3. 建立資料庫
在你本機建立一個檔案夾,然後建立一個 json 檔案,再填入資料即可。
建議檔案名不要出現中文。
例:
建立 json-server-demo 檔案夾,在 json-server-demo 裡建立 db.json 檔案(這些檔案夾和檔案名都可以自由命名)。
db.json 檔案錄入以下資料(資料來自 json-server 官方文檔,你也可以使用自己的資料)
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}
4. 啟動服務
進入 json-server-demo 目錄,打開終端輸入以下指令即可
json-server --watch db.json
首頁和三個接口都可以直接在浏覽器通路,自己打開試試吧。
搞掂!
查(get)
json-server 查詢資料需要使用 GET 方法。
入門篇 隻寫一種查詢方法,其他查詢操作請往下滑,看 進階篇。
上一小節建立了3個接口,我們可以直接在浏覽器、postman或者自己寫JS代碼擷取資料。
http://localhost:3000/posts
http://localhost:3000/comments 和 http://localhost:3000/profile 兩個接口可以自己嘗試,這裡不再啰嗦。
增(post)
json-server 新增資料需要使用 POST 方法。
例:給 posts 添加一條新的資料。
http://localhost:3000/posts
這裡使用 POSt 方法向 /posts 接口傳輸資料,/posts 原本的資料結構是包含 id、title、author 三個字段,id 預設是自增主鍵,不傳的話會預設增加。
此時打開 db.json 檔案看看,可以發現 posts 裡多了一條資料。
需要注意的是:json-server 預設情況下并不會限制你上傳的資料格式和類型,是以需要你嚴格遵循自己設計的資料格式來添加和修改。
删(delete)
json-server 删除資料需要使用 DELETE 方法。
删除的公式是:
http://localhost:3000/{接口名}/{id}
比如現在要删除剛剛上傳的那條資料
{
"title": "leihou",
"author": "雷猴",
"id": 2
}
可以看到剛剛上傳的那條資料的 id 為 2
http://localhost:3000/posts/2
此時打開 db.json 就會發現剛剛删除的那條資料已經沒了。
需要注意的是: 删除成功 Status 會傳回 200;如果删除的資料不存在會傳回 404。
我用 axios 模拟了一下。
删除成功傳回的結果:
删除失敗傳回的結果:
改(put 和 patch)
修改資料分為2個方法:
- put :覆寫
- patch :更新
公式如下所示:
http://localhost:3000/posts/{id}
覆寫(put)
例:把 id 為 1 的資料改成 { "title": "leihou", "author": "雷猴" }
此時打開 db.json 就可以看到 id 為 1 的資料已經發生變化。
注意:原本的資料包含 title 和 author ,使用 put 時必須把這兩個字段都寫上,不然會删掉沒傳的字段。這就是 “覆寫” 的意思。
例如:
此時檢視 db.json 會發現資料被覆寫了
更新(patch)
先還原一下資料,改成如下圖所示:
此時有 title 和 author 字段。
例:使用 patch 方法把 id 為 1 的資料 title 字段的值更改成 hello 。
打開 db.json 檔案檢視一下,會發現隻改了 id 為 1 的 title 值,并沒有删掉 author 這個字段的資料。
進階
啟動參數
我們之前使用 json-server --watch db.json 這條指令啟動了接口項目,其中 json-server 是服務啟動的指令,--watch 是參數,db.json 是目标檔案。
使用下面這條指令可以 檢視配置項:
json-server --help
# 或使用簡寫方式
json-server -h
參數 | 簡寫 | 說明 |
--config | -c | 指定配置檔案 |
--port | -p | 端口号 |
--host | -H | 主機位址 |
--watch | -w | 監聽檔案 |
--routes | -r | 指定路由檔案 |
--middlewares | -m | 指定中間件 |
--static | -s | 設定靜态檔案 |
--read-only | --ro | 隻讀 |
--no-cors | --nc | 禁用跨源資源共享 |
--no-gzip | --ng | 禁止GZIP |
--snapshots | -S | 設定快照目錄 |
--delay | -d | 設定回報延時(ms) |
--id | -i | 設定資料的id屬性(e.g. _id) |
--foreignKeySuffix | --fks | 設定外鍵字尾(如post_id中的_id) |
--quiet | -q | 禁止輸出日志消息 |
--help | -h | 顯示幫助資訊 |
--version | -v | 顯示版本号 |
配置
使用 json-server --help 可以檢視到所有配置項。接下來我示範幾個常見的配置操作。
端口
使用 -p 或者 --port 配置端口号,例如配置 6666 端口
json-server -p 6666 db.json
啟動後
\{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:6666/posts
http://localhost:6666/comments
http://localhost:6666/profile
Home
http://localhost:6666
主機位址
json-server --host 0.0.0.0 db.json
這裡設定了 0.0.0.0 ,之後通過本機 IP 來通路即可。同一個區域網路内的其他裝置也可以通過這個位址來通路。
查詢的常用操作
查詢是日常項目中接觸最多的操作,是以查詢是重點。
普通查詢
用 30秒起步 的那份資料。
查詢 /posts 所有資料
http://0.0.0.0:3000/posts
查詢 /comments 所有資料
http://localhost:3000/comments
查詢 /profile 所有資料
http://localhost:3000/profile
id查詢
将 db.json 的内容修改一下。
{
"posts": [
{
"id": 1,
"title": "文章111",
"author": "張三"
},
{
"id": 2,
"title": "文章222",
"author": "李四"
}
]
}
此時隻有 posts 接口,裡面有2條資料,id 分别為 1 和 2。
查詢的公式是:
http://localhost:3000/posts/{id}
查詢 id 為 2 的資料
http://localhost:3000/posts/2
條件查詢
準備以下資料。
{
"posts": [
{
"id": 1,
"title": "文章111",
"author": "張三"
},
{
"id": 2,
"title": "文章222",
"author": "李四"
},
{
"id": 3,
"title": "文章333",
"author": "張三"
}
]
}
可以看到裡面有 2條張三 的資料,1條李四 的資料。
單一條件查詢
查找 author 為 張三 的所有資料。
查詢 author 是 張三 的資料
http://localhost:3000/posts?author=張三
在 http://localhost:3000/posts 後面加一個 ? ,然後寫上篩選條件即可。
多條件查詢(且)
上面的資料,有2條張三的。
這次要篩選的是 author = 張三 且 title = 文章333 的資料
http://localhost:3000/posts?author=張三&title=文章333
符合條件賽選的時候,使用 & 号添加條件。
多條件查詢(或)
這次要篩選的是 title = 222 和 title = 333 這兩條資料出來。
http://localhost:3000/posts?title=文章222&title=文章333
重複使用 title ,會把符合條件的都篩查出來。
當然,我們還可以使用 模糊查詢 來達到類似的效果,稍後會講到。
深度屬性查詢
這裡需要準備另一份資料才能展示這個知識點。
資料内容如下
{
"posts": [
{
"id": 1,
"title": "文章111",
"authorInfo": {
"name": "張三",
"age": 20
}
},
{
"id": 2,
"title": "文章222",
"authorInfo": {
"name": "李四",
"age": 24
}
}
]
}
可以看到 authorInfo 裡面還有子屬性。
查詢 authorInfo.name = 張三 的資料。
http://localhost:3000/posts?authorInfo.name=張三
這裡需要使用 . 的方式來通路子級資料,有點像 js 用點文法通路對象屬性那樣。
工作中我遇到這樣的接口不多。
分頁查詢
使用 _page 和 _limit(可選) 對資料進行分頁。需要注意,_page 和 _limit 前面都要有下劃線。
- _page:頁碼
- _limit:每頁的資料量
修改 db.json 裡的資料友善測試分頁功能,如下所示
{
"comments": [
{ "id": 1, "body": "some comment 1", "postId": 1 },
{ "id": 2, "body": "some comment 2", "postId": 1 },
{ "id": 3, "body": "some comment 3", "postId": 2 },
{ "id": 4, "body": "some comment 4", "postId": 3 },
{ "id": 5, "body": "some comment 5", "postId": 1 },
{ "id": 6, "body": "some comment 6", "postId": 3 },
{ "id": 7, "body": "some comment 7", "postId": 3 },
{ "id": 8, "body": "some comment 8", "postId": 1 },
{ "id": 9, "body": "some comment 9", "postId": 2 },
{ "id": 10, "body": "some comment 10", "postId": 2 },
{ "id": 11, "body": "some comment 11", "postId": 3 },
{ "id": 12, "body": "some comment 11", "postId": 1 }
]
}
準備了12條資料。
需要擷取第2頁的資料,每頁3條:
http://localhost:3000/comments?_page=2&_limit=3
除了要傳回的資料外,還會在 Headers 裡傳回 總數;第一個、前一個、下一個、最後一個的連結。我用 axios 發個請求示範一下。
axios.get('http://localhost:3000/comments', {
params: {
_page: 2,
_limit: 3
}
})
.then(res => {
console.log(res)
})
.catch(err => {
console.error(err)
})
傳回結果如下所示
x-total-count 存放總數。
link 字段裡存放的是 第一個、前一個、下一個、最後一個 的連結位址
"
<http://localhost:3000/comments?_page=1&_limit=3>; rel=\"first\", <http://localhost:3000/comments?_page=1&_limit=3>; rel=\"prev\", <http://localhost:3000/comments?_page=3&_limit=3>; rel=\"next\", <http://localhost:3000/comments?_page=4&_limit=3>; rel=\"last\"
"
排序查詢
需要添加 排序的标記 ( _sort ),然後設定 排序規則 ( _order )。
其中,排序規則有 升序 ( asc ) 和 降序 ( desc ) 。
http://localhost:3000/{接口名}?_sort=要排序的字段名&_order=排序規則
以這份資料為例:
{
"comments": [
{ "id": 11, "body": "some comment 1", "postId": 1 },
{ "id": 2, "body": "some comment 2", "postId": 1 },
{ "id": 3, "body": "some comment 3", "postId": 2 },
{ "id": 10, "body": "some comment 4", "postId": 3 },
{ "id": 7, "body": "some comment 5", "postId": 1 },
{ "id": 6, "body": "some comment 6", "postId": 3 },
{ "id": 5, "body": "some comment 7", "postId": 3 },
{ "id": 8, "body": "some comment 8", "postId": 1 },
{ "id": 9, "body": "some comment 9", "postId": 2 },
{ "id": 4, "body": "some comment 10", "postId": 2 },
{ "id": 1, "body": "some comment 11", "postId": 3 },
{ "id": 12, "body": "some comment 11", "postId": 1 }
]
}
id 的排序是亂的,如果使用普通的方式請求回來的資料是原模原樣傳回的。
升序
以 id 為參考字段進行升序排列傳回給用戶端。
http://localhost:3000/comments?_sort=id
或
http://localhost:3000/comments?_sort=id&_order=asc
傳回的結果就會以 id 為參考字段升序排好。
普通升序排列的話,_order=asc 可以不傳。隻需指定 參考字段 ( _sort ) 即可。
降序
降序必須填好 _order=desc 。
http://localhost:3000/comments?_sort=id&_order=desc
多字段排序
這次的需求是:
- 首先按 postId 升序排列
- 在 1 的基礎上再對 id 進行倒序排列
多個字段用 , 分格。
http://localhost:3000/comments?_sort=postId,id&_order=asc,desc
傳回結果:
{
"comments": [
{ "id": 12, "body": "some comment 11", "postId": 1 },
{ "id": 11, "body": "some comment 1", "postId": 1 },
{ "id": 8, "body": "some comment 8", "postId": 1 },
{ "id": 7, "body": "some comment 5", "postId": 1 },
{ "id": 2, "body": "some comment 2", "postId": 1 },
{ "id": 9, "body": "some comment 9", "postId": 2 },
{ "id": 4, "body": "some comment 10", "postId": 2 },
{ "id": 3, "body": "some comment 3", "postId": 2 },
{ "id": 10, "body": "some comment 4", "postId": 3 },
{ "id": 6, "body": "some comment 6", "postId": 3 },
{ "id": 5, "body": "some comment 7", "postId": 3 },
{ "id": 1, "body": "some comment 11", "postId": 3 }
]
}
符合需求。
切片查詢
切片的意思是指定 頭 和 尾 ;也可以指定 頭 和 片段長度 。
用到的關鍵字有:
- _start:開始位置(下标,從0開始)
- _end:結束位置
- _limit:片段長度
總數 會放在 headers 裡。
以這份資料為例
{
"comments": [
{ "id": 1, "body": "some comment 1", "postId": 1 },
{ "id": 2, "body": "some comment 2", "postId": 1 },
{ "id": 3, "body": "some comment 3", "postId": 2 },
{ "id": 4, "body": "some comment 4", "postId": 3 },
{ "id": 5, "body": "some comment 5", "postId": 1 },
{ "id": 6, "body": "some comment 6", "postId": 3 },
{ "id": 7, "body": "some comment 7", "postId": 3 },
{ "id": 8, "body": "some comment 8", "postId": 1 },
{ "id": 9, "body": "some comment 9", "postId": 2 },
{ "id": 10, "body": "some comment 10", "postId": 2 },
{ "id": 11, "body": "some comment 11", "postId": 3 },
{ "id": 12, "body": "some comment 11", "postId": 1 }
]
}
需求:傳回下标從 2-6 的資料
使用 _start 和 _end 的方式
http://localhost:3000/comments?_start=2&_end=6
使用 _start 和 _limit 的方式
http://localhost:3000/comments?_start=2&_limit=4
範圍查詢
範圍查詢包括 大于等于、小于等于、不等于 三種情況。
大于等于 _gte
大于等于 使用的關鍵字是 _gte 。注意,前面有個下劃線的。
需求:查詢 comments 接口 id 大于等于 4 的資料
http://localhost:3000/comments?id_gte=4
小于等于 _lte
需求:查詢 comments 接口 id 小于等于 4 的資料
http://localhost:3000/comments?id_lte=4
聯合一起使用
需求:查詢 comments 接口 id 大于等于 4 且 小于等于 6 的資料
http://localhost:3000/comments?id_gte=4&id_lte=6
不等于 _ne
需求:查詢 comments 接口 id 不等于 2 的資料
http://localhost:3000/comments?id_ne=2
模糊查詢
模糊查詢的關鍵字是 _like。
需求:查詢 comments 接口 body 包含 1 的資料
全文查詢
全文查詢的關鍵字是 q
準備以下資料比較好示範
{
"authors": [
{ "id": 1, "name": "zhangsan", "age": 18},
{ "id": 2, "name": "lisi", "age": 21},
{ "id": 3, "name": "wangwu", "age": 24}
]
}
查詢所有字段中包含 2 的資料出來
http://localhost:3000/authors?q=2
因為 id 為 3 的那條資料裡 age 是 24 ,也算是包含了 2 。
外鍵關聯查詢
外鍵查詢需要 2個接口 關聯查詢。
準備以下資料友善示範
{
"posts": [
{ "id": 1, "title": "文章111", "author": "張三" },
{ "id": 2, "title": "文章222", "author": "李四" }
],
"comments": [
{ "id": 1, "body": "some comment 1", "postId": 1 },
{ "id": 2, "body": "some comment 2", "postId": 1 },
{ "id": 3, "body": "some comment 3", "postId": 2 }
]
}
posts 裡有2條資料。
comments 裡有3條資料,其中每條資料都有一個 postId,是對應 posts 每條資料的 id。
需求:查詢 posts 裡 id 為 1 的所有 comments 内容
http://localhost:3000/posts/1/comments
關系拼裝
關系拼裝可以把關聯的2個接口的資料拼接起來并傳回。
其中有2種查詢關系:
- 包含子資源 _embed
- 包含父資源 _expand
準備以下資料友善示範
{
"posts": [
{ "id": 1, "title": "文章111", "author": "張三" },
{ "id": 2, "title": "文章222", "author": "李四" }
],
"comments": [
{ "id": 1, "body": "some comment 1", "postId": 1 },
{ "id": 2, "body": "some comment 2", "postId": 1 },
{ "id": 3, "body": "some comment 3", "postId": 2 }
]
}
包含子資源 _embed
http://localhost:3000/posts?_embed=comments
還可以拼接多個條件。
需求:在 comments 裡,把 posts 裡 id 為 2 的資料找出來并拼接起來
http://localhost:3000/posts/2?_embed=comments
包含父資源 _expand
http://localhost:3000/comments?_expand=post
複制代碼
配置路由
有時候我們的 api位址 可能不像上面所有案例中那麼簡單,此時就可以使用 自定義路由 的方法來模拟。
比如模拟下面這個接口:
http://localhost:3000/api/users/1
實作的步驟如下所示:
- 建立 routes.json 檔案(也可以不叫這個名字)
- 啟動服務時使用 --routes 參數
1、建立 routes.json ,并輸入以下内容。
{
"/api/*": "/$1"
}
2、啟動服務
json-server db.json --routes routes.json
3、通路
http://localhost:3000/api/posts
靜态資源
靜态資源包含 html 、css 、js 、圖檔、視訊等資源。
配置
配置方式分2種:
- 預設配置
- 指定資源位置
預設配置
需要在根目錄下建立 public 檔案夾,裡面放入 html 等檔案。
然後在浏覽器通路一下 http://localhost:3000/
你也可以加入自己的 css 和 js 進行設計互動。
指定資源位置
json-server 配資靜态資源的預設方式是在根目錄下建立 public 檔案夾,然後裡面放入靜态資源。
但如果你不想使用 public 作為靜态資源的檔案夾,也可以自己起過另一個名字,然後在啟動環境時使用 --static 來指定目标目錄就行了。
比如我建立了一個 some-other-dir 作為靜态資源的目錄,使用以下指令指定以下即可。
json-server db.json --static ./some-other-dir
多媒體資源
除了放 html 、css 和 js 資源外,還可以放圖檔和視訊。
我以圖檔為例,我在 public 目錄下添加一個圖檔。
直接在 http://localhost:3000/ 後面跟着 圖檔檔案名 即可。
其他
生成動态資料
如果我們要模拟100條資料,甚至更多的話,建立 json 檔案然後一條一條錄入的方式真的很不合時。
此時我們可以使用 js 通過循環的方式來實作資料建立。
1、首先在根目錄下建立一個 db.js 的檔案。
2、輸入一下内容
module.exports = () => {
const data = { users: [] }
// 建立 100 個 users
for (let i = 0; i < 100; i++) {
data.users.push({ id: i, name: `user${i}` })
}
return data
}
3、運作 js 檔案
json-server db.js
4、查詢一下
http://localhost:3000/users
100條資料就直接生成了。
需要什麼字段可以自己在 js 檔案裡配置。
查詢整個資料庫
通路以下位址可以獲得整個資料庫的資料。
http://localhost:3000/db
遠端模式
如果想使用網際網路上的資料,也可以直接運作 json-server 然後加上遠端的位址即可。
json-server http://jsonplaceholder.typicode.com/db
如果本文能給您帶來幫助,請幫我 點個贊 呗~