使用json-server模拟一个假接口来获取数据
很多时候,前后端开发不同步,我们又想使用接口发送请求,来查看我们自己的代码是否正确。这个时候,json-server就是一个很好的工具了。
json-server:
这是一个轻量级的 , 用来模拟假接口的工具 。它 根据一个json文件,提供假数据接口。
由于是轻量级,并且不需要写一行代码就可以实现假接口,所以也有它的缺陷,比如:不能删除多条数据。
使用:
- 准备一个data.json 文件数据 ;
- 全局安装 :
npm i json-server -g
(作为一个工具使用) - 使用 :
json-server data.json
,就开启了,通过地址可以直接访问
使用json-server模拟假数据接口,遵循REST API 格式
- 查询 GET
- 添加 POST
- 删除 DELETE
- 修改 PUT/PATCH
我模拟的假接口地址:http://localhost:3000/list
-
get
-
post
- 添加数据 http://localhost:3000/list
- 参数 : {name:‘zs’, done:false} , id会自动根据最后一个的id添加,不需要写
-
delete
- 删除某一条数据 http://localhost:3000/list/1
-
put/patch
-
修改某一条数据 http://localhost:3000/list/1
put : {name:‘吃鸡’, done:’'true}; 整条都要写(不修改的地方也要写,因为这条数据会把原来的数据覆盖)
patch : {done:true}; 哪里需要修改写哪里(在原来的基础上修改)
-
使用axios 发送请求
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中,专门用来发送ajax请求的一个工具(库)
使用:
-
本地安装
npm i axios
-
引入 axios
<script src='...axios.js'></script>
-
简单使用:
-
axios.get( url , config(对象) )
//获取全部数据 axios.get("http://localhost:3000/list").then(res => { console.log(res.data); }); //获取单条数据(id=2) axios.get("http://localhost:3000/list/2").then(res => { console.log(res.data); }); //或者: axios.get("http://localhost:3000/list", { params: { id: 2 } }).then(res => { console.log(res.data[0]); });
axios.post(url,data, config)
注意 : id可以不用写,会自动在最后一个id的基础上 +1
//post添加一条数据 axios.post("http://localhost:3000/list", { name: "吃鸡", done: false }).then(res => { console.log(res.data); });
axios.delete( url , config )
删除对应id的数据,(json-server不支持在配置项中写参数删除数据)
//delete删除一条数据(删除id=3的数据) axios.delete("http://localhost:3000/list/3").then(res => { console.log(res); });
-
axios.put(url, data , config)
-
axios.patch(url, data, config)
put 和 patch 的区别在于 :
put 修改数据需要把所有的数据都写上,包括修改的和不修改的,因为put修改的数据是整条覆盖原来的.
patch 修改数据只需要写需要修改的内容即可, 哪里需要修改写哪里
//put修改某条数据 axios.put("http://localhost:3000/list/4", { done: false, name: "ttj" }).then(res => { console.log(res); }); //patch修改某条数据 axios.patch("http://localhost:3000/list/5", { done: true }).then(res => { console.log(res); });
little-demo:
<script src="./node_modules/axios/dist/axios.js"></script> <script> //获取全部数据 // axios.get("http://localhost:3000/list").then(res => { // console.log(res.data); // }); //获取单条数据(id=2) // axios.get("http://localhost:3000/list/2").then(res => { // console.log(res.data); // }); //或者: // axios.get("http://localhost:3000/list", { // params: { // id: 2 // } // }) // .then(res => { // console.log(res.data[0]); // }); //post添加一条数据 // axios // .post("http://localhost:3000/list", { // name: "吃鸡", // done: false // }) // .then(res => { // console.log(res.data); // }); //delete删除一条数据(删除id=3的数据) // axios.delete("http://localhost:3000/list/3").then(res => { // console.log(res); // }); //修改某一条数据 //put修改 // axios // .put("http://localhost:3000/list/4", { // done: false, // name: "ttj" // }) // .then(res => { // console.log(res); // }); //patch修改 axios .patch("http://localhost:3000/list/5", { done: true }) .then(res => { console.log(res); }); </script>