10_axios.html 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Axios</title>
  8. <!-- 引入axios -->
  9. <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  10. </head>
  11. <body>
  12. <button id="btn1">按钮1</button>
  13. <button id="btn2">按钮2</button>
  14. <script>
  15. //console.log(axios);
  16. document.getElementById("btn1").onclick = () =>{
  17. //直接调用axios发送请求
  18. //axios(config)
  19. axios({
  20. method:"post",
  21. url:"http://localhost:3000/students",
  22. data:{
  23. name:"唐僧",
  24. age:18,
  25. gender:"男",
  26. address:"女儿国"
  27. }
  28. }).then((res) =>{
  29. //res是axios封装过
  30. //console.log(res);
  31. console.log(res.data);
  32. }).catch((err) => {
  33. console.log("出错了",err);
  34. })
  35. }
  36. document.getElementById("btn2").onclick = () =>{
  37. //直接调用axios发送请求
  38. //axios(config)
  39. axios({
  40. method:"get",
  41. url:"http://localhost:3000/students",
  42. }).then((res) =>{
  43. //axios默认只会在响应状态码为2xx时才会调用then
  44. //res是axios封装过
  45. //console.log(res);
  46. console.log(res.data);
  47. }).catch((err) => {
  48. console.log("出错了",err);
  49. })
  50. }
  51. </script>
  52. </body>
  53. </html>