JSON-Server
一個在前端本地運行,可以存儲json數據的server。前端開發可以模擬服務端接口數據,在本地搭建一個JSON服務,自己產生測試數據。
- 使用npm全局安裝json-server :npm install -g json-server
- 可以通過查看版本號,來測試是否安裝成功:json-server -v
- 創建json數據——db.json
在任意一個文件夾下(此處假設創建一個server文件夾),進入到該文件夾里面,執行代碼 json-server --watch db.json - 此時文件夾下多出一個db.json文件
- 啟動
json-server --watch db.json
,訪問 http://localhost:3000/ - 分別點擊/posts /comments /profile /db鏈接,我們可以看到訪問不同URL返回不同的json數據。其中 /db返回的是整個json文件的數據。
- 修改端口號
默認3000--port 3004
或者在db.json同級文件夾新建一個package.json,在script配置添加運行命令:
{"scripts": {"mock": "json-server db.json --port 3004"}
}
//運行時, 直接在當前文件夾下執行 npm run mock
- 操作數據 | 增刪改查
json-server 支持 restful 風格的api,可以通過不同的請求方式,對數據進行增刪改查等不同的操作。
先修改db.json文件:
{"users": [{"id": 1,"name": "liaoyi","phone": "13246566776","age": 22,"classId": "1002"},{"name": "林更新","age": "44","id": 4,"classId": "1003"},{"name": "李響","phone": "18779756778","age": "26","id": 5,"classId": "1003"},{"name": "陳溫柔","phone": "18779756000","age": "22","id": 6,"sex": "0","classId": "1004"},{"name": "夏琪","phone": "13246579999","age": "22","id": 7,"classId": "1004"}],"class": [{"id": "1","title": "前端","staff": ["1002","1004"]},{"id": "2","title": "后端","staff": ["1003"]}],"fruits": [{"id": 1,"name": "蘋果","price": 1.28},{"id": 2,"name": "橘子","price": 3.88},{"id": 3,"name": "寧夏西瓜","price": 1.98},{"id": 4,"name": "麒麟西瓜","price": 3.98},{"id": 5,"name": "紅蛇果","price": 2.5},{"id": 6,"name": "黑皮西瓜","price": 0.98},{"id": 7,"name": "紅心火龍果","price": 2.69},{"id": 8,"name": "國產火龍果","price": 1.69},{"id": 9,"name": "海南荔枝","price": 9.9},{"id": 10,"name": "陜西冬棗","price": 5.39},{"id": 11,"name": "軟籽石榴","price": 2.39},{"id": 12,"name": "蜜橘","price": 1.99},{"id": 13,"name": "海南香蕉","price": 1.45}],"person": [{"name": {"firstname": "liao","lastname": "yi"},"pwd": "qwerst54"},{"name": {"firstname": "wang","lastname": "wu"},"pwd": "adasff11"}]
}
- get 獲取數據
瀏覽器可以直接訪問GET請求,可以直接在瀏覽器訪問就能看到返回的json數據。
獲取所有用戶數據(對象數組): http://localhost:3004/users
獲取所有水果數據:http://localhost:3004/fruits
獲取數據
根據 id 獲取 users 數據:http://localhost:3004/users/1
//get請求的query參數
http://localhost:3004/users?id=1//傳入不同的條件
// 查找名字為 'liaoyi' 的用戶
http://localhost:3004/users?name=liaoyi//多個條件 用&符號連接:
http://localhost:3004/fruits?name=橘子&price=3.88
//甚至還可以使用對象取屬性值 obj.key 的方式http://localhost:3004/person?name.firstname=liao//分頁采用 _page 來設置頁碼,
// _limit 來控制每頁顯示條數。
//如果沒有指定 _limit ,默認每頁顯示10條。
http://localhost:3004/fruits?_page=1&_limit=5
http://localhost:3004/fruits?_page=1&_limit=10
http://localhost:3004/fruits?_page=2&_limit=5//排序采用 _sort 來指定要排序的字段,
// _order 來指定排序是正排序還是逆排序(asc | desc ,默認是asc)。
http://localhost:3004/fruits?_sort=price
http://localhost:3004/fruits?_sort=price&_order=desc//獲取局部數據
//_start 來指定開始位置, _end 來指定結束位置、
//或者_limit指定從開始位置起往后取幾個數據。類似Array.slice() 方法
# 使用 _end
http://localhost:3004/fruits?_start=2&_end=4# 使用 _limit
http://localhost:3004/fruits?_start=2&_limit=4//獲取符合某個范圍的數據
1. 使用 _gte 和 _lte 來設置一個取值范圍 :
2. 使用 _ne 來獲取不包含某個值的數據
3. 采用 _like 來設置匹配某個字符串(或正則表達式)
http://localhost:3004/fruits?id_gte=4&id_lte=6
http://localhost:3004/fruits?id_ne=1&id_ne=10
http://localhost:3004/fruits?name_like=果//搜索功能 采用 q 來設置搜索內容:
http://localhost:3004/fruits?q=瓜
- 除get請求外,其他請求方式需要我們通過 api 調試工具或者代碼的方式來使用。如apifox
<template><el-button @click="add"> 發送請求 </el-button>
</template><script setup>import axios from 'axios'const url = 'http://localhost:3004/users'const add = async () => {const data = {name: '林更新',phone: '18779756000',age: '22'}const { data: res } = await axios({ method: 'post', url, data })console.log('res', res)}
</script><template><el-button @click="deleteUser"> 刪除用戶 </el-button>
</template><script setup>
import axios from 'axios'const userId = 3
const url = `http://localhost:3004/users/${userId}`
const deleteUser = async () => {const res = await axios({ method: 'delete', url })console.log('res', res)
}
</script>
PUT方法會更新整個資源對象,前端沒有給出的字段,會自動清空。但是使用put修改后會有一個問題,只會保留提交的字段,沒有提交的字段在json中將會被刪除
patch 修改數據 :只修改請求的字段,沒有請求的字段將會被保留。
<template><el-button @click="reviseUser"> put 修改用戶 </el-button>
</template><script setup>
import axios from 'axios'const userId = 4
const url = `http://localhost:3004/users/${userId}`
const reviseUser = async () => {const data = {"name": "林更新","age": "44"}const res = await axios({ method: 'put', url, data })console.log('res', res)
}
</script><template><el-button @click="reviseUser"> patch修改用戶 </el-button>
</template><script setup>
import axios from 'axios'const userId = 8
const url = `http://localhost:3004/users/${userId}`
const reviseUser = async () => {const data = {name: "陳溫柔",age: "22",sex: "0"
}const res = await axios({ method: 'patch', url, data })console.log('res', res)
}
</script>
- 多表查詢 | 關聯檢索
- 向上關聯
通過 _expand 方式檢索關聯父級數據,多對一關系,所以條件是單數。
這里的 _expand=class 匹配即和 users 對象中的 classId做關聯,但是已經存在classId字段則寫出 class, 比如檢索的是 repaId 寫成 repa - 通過 _embed 方式檢索關聯子級數據
注意: 這里_embed 需要和子表名 (要關聯的子集屬性名) 匹配。一對多關系,所以匹配條件是負數。
//向上關聯父級數據
//class 是一個別名
http://localhost:3004/users?_expand=class
//res:
[{"id": 1,"name": "liaoyi","phone": "13246566776","age": 22,"classId": "1","class": {"id": "1","title": "前端","staff": ["7","6","1"]}},{"name": "林更新","age": "44","id": 4,"classId": "2","class": {"id": "2","title": "后端","staff": ["4","5"]}},{"name": "李響","phone": "18779756778","age": "26","id": 5,"classId": "2","class": {"id": "2","title": "后端","staff": ["4","5"]}},{"name": "陳溫柔","phone": "18779756000","age": "22","id": 6,"sex": "0","classId": "1","class": {"id": "1","title": "前端","staff": ["7","6","1"]}},{"name": "夏琪","phone": "13246579999","age": "22","id": 7,"classId": "1","class": {"id": "1","title": "前端","staff": ["7","6","1"]}}
]
//向下關聯子級數據
http://localhost:3004/classes?_embed=users
//res:
[{"id": "1","title": "前端","staffIds": ["1001","1004","1005"],"users": [{"id": "1001","name": "liaoyi","phone": "13246566776","age": 22,"classId": "1"},{"name": "陳溫柔","phone": "18779756000","age": "22","id": "1004","sex": "0","classId": "1"},{"name": "夏琪","phone": "13246579999","age": "22","id": "1005","classId": "1"}]},{"id": "2","title": "后端","staffIds": ["1002","1003"],"users": [{"name": "林更新","age": "44","id": "1002","classId": "2"},{"name": "李響","phone": "18779756778","age": "26","id": "1003","classId": "2"}]}
]
- 靜態部署
新增配置文件 config.json 并寫入
{"port": "3000", // 設置端口號"watch": true, // 是否開啟監聽"static": "./public/", // 靜態資源目錄"read-only": false, // 是否只讀"no-cors": true, // 是否支持跨域"no-gzip": false // 是否開啟壓縮
}
//啟動命令
json-server --watch data.json config.json//或者放入package.json+npm run mock
{"scripts": {"mock": "json-server --watch data.json config.json"}
}
mock.js
- Mock.js + json-server 模擬數據
- 創建一個文件夾名為 mock_json
- 進入文件夾后初始化package.json 文件
- 下載依賴
mkdir mock_json
cd mock_json
npm init
npm install json-server mockjs
- 添加啟動腳本
{"name": "mock_json","scripts": {"dev": "json-server --watch db.js --port 3000"},"dependencies": {"json-server": "^0.17.4","mockjs": "^1.1.0"}
}
- 新建 db.js 文件
const Mock = require('mockjs')const data = Mock.mock({'users|10-20': [{'id|+1': '1','name': '@name','sex|1': ['男', '女'],'age|18-60': 1,'address': '@county(true)','phone': /^1[34578]\d{9}$/,'email': '@email','birthday': '@date','avatar': '@image(200x200, #50B347, #FFF, #78C3FC)','desc': '@cparagraph(1, 3)'}],'products|122000': [{'id|+1': 1,'name': '@word(3,5)','price': '@integer(100,999)','quantity': '@integer(1,50)','brief': '@cparagraph(1, 3)'}],
})
// 想要用 json-server 識別mockjs的模擬數據內容,需要使用 module.exports 進行模塊的對外暴露,并且暴露的類型必須是函數
module.exports = () => data/* 上面👆 products 有十二萬數據,不能直接打開瀏覽器訪問http://localhost:3000/products,瀏覽器會奔潰的需要使用查詢參分頁查詢如: http://localhost:3000/products?_page=1&_limit=10 */
- 啟動項目
npm run dev
注意??:
- 想要用 json-server 識別mockjs的模擬數據內容,需要使用 module.exports 進行模塊的對外暴露,并且暴露的類型必須是函數。
- 上面 products 我們模擬了十二萬條數據,啟動時會有點慢,并且不能直接使用瀏覽器訪問http://localhost:3000/products,瀏覽器會奔潰的。需要使用查詢參分頁查詢, 如:http://localhost:3000/products?_page=1&_limit=10