1.先创建一些button按钮
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>axios基本使用</title> <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script> </head> <body> <div class="container"> <h2 class="page-header">基本使用</h2> <button class="btn btn-primary"> 发送GET请求 </button> <button class="btn btn-warning"> 发送POST请求 </button> <button class="btn btn-success"> 发送 PUT 请求 </button> <button class="btn btn-danger"> 发送 DELETE 请求 </button> </div> </body> </html>
2.给一个按钮绑定一个GET请求事件(同时还要设置响应)
<script> const btns = document.querySelectorAll("button"); btns[0].onclick = function() { axios({ method: "GET", url: "http://localhost:3000/posts/2" }).then(response => { console.log(response); }) } </script>
效果图如下:
3.给一个按钮绑定一个POST请求事件(同时还要设置响应)
请求体内容不需要设置id属性,直接将要输入的数据输入即可
btns[1].onclick = function() { axios({ method: "POST", url: "http://localhost:3000/posts", data: { title: "刘丽娟小姐,我爱你", author: "劳志驰" } }).then(response => { console.log(response); }) }
这个时候在db.json文件当中就会自动显示出我们要添加我数据
4.给按钮绑定一个PUT请求
记得要在uri后面加上具体的id路径,这样子才能进行修改
btns[2].onclick = function() { axios({ method: "PUT", url: "http://localhost:3000/posts/3", data: { title: "刘丽娟小姐,爱你一辈子", author: "劳志驰" } }).then(response => { console.log(response); }) }
5.给按钮绑定一个Delete请求
btns[3].onclick = function() { axios({ method: "delete", url: "http://localhost:3000/posts/3", }).then(response => { console.log(response); }) }
记得在delete的时候要直接写明id的属性大小,方便直接删除