json-server && axios

51 阅读1分钟

一. Json Server

json-server 可以模拟一个小型的后端服务器,即在本地自己的端口开启该服务后,可以模拟向其所在端口请求数据,它会返回的。

二. 使用方法
  • npm i -g json-server
  • 准备一个 json 文件,eg: db.json
  • 在自己的终端执行命令:json server --watch db.json
  • 发送请求

三. axios 的几种请求

(1) 取数据 get

axios.get("http://localhost:8000/rights") .then((res)=>{ })

(2) 增加数据 post

axios.post(url,{增加的数据}).then()

axios.post("http://localhost:8000/rights", { title : "yhx", age : 19 } ) .then((res)=>{ })

(3) 更新数据 put [替代式更新]

axios.post(url/要更新的数据的id,{更新的数据}).then()

1945.png

(4) 更新数据 patch [局部式更新]

1945.png

(5) 删除数据 delete

1946.png

四. 关联请求

<1> 向下关联 _embed

例如,现在有发布文章的数据,也有文章评论的数据,两者是分开的,但如果我们此时想要把每条评论加入到对应的文章数据中返回,方便我们做展示,就可以用向下关联。

1947.png

<2> 向上关联 _expand

例如,我们想通过评论,找到该评论所关联的新闻的信息,就可以用向上关联!!

1948.png