[筆記][vue+axios+json-server][404]常用方法撰寫

Athem
2 min readDec 18, 2019

--

使用json-server做假server不能像過去寫後端一樣暴力只用post()get()。若新增一筆資料用post()整個data都會被覆寫只剩新增的該筆資料,這就是嚴謹的RESTFul風格吧…記錄一下寫法,以防以後忘記…

有關Json-Server

首先,db.json裡每個陣列的元素一定要有id,沒有的話會報錯

// db.json
{
"lists": [
{ "id": "1", "a": "value", "flag": true },
{ "id": "2", "a": "value", "flag": false },
{ ... },
],
...
}

方法使用(新/刪/修/查)

新:post()

新增資料。

// 新增一筆資料
const obj = { id:3, a:"aaa" }
this.axios.post("/api",obj).then( res => { ... })

刪:delete()

刪除某筆資料。

// 在網址後面放要刪除資料的id
const id = 1
this.axios.delete(`/api/${id}`).then( res => { ... }) // 刪除id=1資料

修:patch()

改變某筆資料。

// 網址後放要修改的id,參數放要修改的值。
const obj = { a:"bbb"}
this.axios.patch(`/api/${id}`,obj).then( res => { ... })

查:get()

取資料

// 取全部資料,不需要參數
this.axios.get("/api").then( res => { ... } )
// 取篩選後資料,參數為Object
const obj = {flag: false}
this.axios.get("/api", { params:obj }).then( res => { ... } )
//只會抓列表裡flag:false的資料

心得

目前用到上面的幾種方式而已,有新的在上來補吧~話說從後端跑來寫前端滿常遇到挫折的,不過也很驚訝,現在前端框架的架構跟後端滿雷同的,真的很強大噎~

--

--