什么是json-server
一個(gè)在前端本地運(yùn)行乾蛤,可以存儲(chǔ)json數(shù)據(jù)的server
模擬服務(wù)端接口數(shù)據(jù)斗搞,一般用在前后端分離后,前端人員可以不依賴API開發(fā)力喷,而在本地搭建一個(gè)JSON服務(wù),自己產(chǎn)生測(cè)試數(shù)據(jù)渴肉。
參考網(wǎng)址: http://www.reibang.com/p/bdbbd3314cf3
安裝
npm install -g json-server
使用
準(zhǔn)備好db.json
- 為對(duì)象類型冗懦,每個(gè)鍵名即為將來的接口名爽冕,屬性值是數(shù)組
- 唯一標(biāo)識(shí)字段為"id"
{
"product":[],
"users":[]
}
啟動(dòng)
json-server --watch db.json
也可自定義端口
json-server --watch --port 3001 db.json
//默認(rèn)訪問接口為:
localhost:3000
可在前端配置訪問基本路徑
const baseUrl = "http://localhost:3000"
增
let newProduct = {
proName: '手機(jī)',
price: 300
}
axios.post(`${baseUrl}/product`, newProduct)
.then(res => {
console.log(res);
})
刪
axios.delete(`${baseUrl}/product/5`)
.then(res => {
console.log(res);
})
改
let newData = {
proName: '手套',
price: 10
}
axios.put(`${baseUrl}/product/6`, newData)
.then(res => {
console.log(res);
})
查
axios.get(`${baseUrl}/product`)
.then(res => {
console.log(res);
})
json-server內(nèi)置實(shí)現(xiàn)的過濾字段
「注」過濾字段仇祭,只針對(duì)數(shù)組數(shù)據(jù)。(畢竟只有數(shù)組需要過濾)
_gte: 大于等于
_lte: 小于等于
_ne: 不等于
_like: 包含
例:http://localhost:3001/data1?age_gte=20&age_lte=30
_page:訪問第幾頁(yè)數(shù)據(jù)
_limit:一頁(yè)多少條(默認(rèn)一頁(yè)10條)
_sort:設(shè)定排序字段
_order:設(shè)定排序的方式(升序:asc颈畸;降序:desc乌奇;默認(rèn)升序)
例:http://localhost:3001/data1?_sort=age&_order=asc
q:全文搜索關(guān)鍵字
axios.get("http://localhost:3000/product")
axios.get("http://localhost:3000/user")
axios.get("http://localhost:3000/user/6")
axios.get("http://localhost:3000/product?price=90")
axios.get("http://localhost:3000/product?price_gte=90")
axios.get("http://localhost:3000/product?_page=2&_limit=3&_sort=id&_order=desc")
axios.get("http://localhost:3000/product?proName_like=機(jī)")
axios.get("http://localhost:3000/product?q=機(jī)")