13_axios实例.html 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. axios.defaults.baseURL = "http://localhost:3000"
  16. axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem("token")}`;
  17. //axios实例相当于axios的一个副本,它的功能和axios一样
  18. //axios的默认配置在实例也同样会生效
  19. //但是我们可以在单独修改axios实例的默认配置,实例默认配置的修改,只对当前实例有效
  20. //对其他实例和axios无效
  21. // const instance = axios.create({
  22. // baseURL:"http://localhost:4000"
  23. // })
  24. //或者采用下面的方式进行修改
  25. const instance = axios.create()
  26. instance.defaults.baseURL = "http://localhost:4000"
  27. document.getElementById("btn1").onclick = () =>{
  28. instance.get("students")
  29. .then((res) => {
  30. console.log(res.data);
  31. })
  32. .catch((err) => {
  33. console.log("出错了",err);
  34. })
  35. }
  36. </script>
  37. </body>
  38. </html>