14_拦截器.html 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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>拦截器</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. <script>
  14. axios.defaults.baseURL = "http://localhost:3000"
  15. //axios的拦截器可以对请求或响应进行拦截,在请求发送前和响应读取前处理数据
  16. //拦截器只对当前的实例有效
  17. // 添加请求拦截器
  18. axios.interceptors.request.use(
  19. function (config) {
  20. console.log("拦截器执行了");
  21. //config 表示axios中的配置对象
  22. //console.log(config);
  23. //config.data.name = "猪二爷"
  24. config.headers["Authorization"]= `Bearer ${localStorage.getItem("token")}`
  25. // 在发送请求之前做些什么
  26. return config;
  27. }, function (error) {
  28. // 对请求错误做些什么
  29. return Promise.reject(error);
  30. });
  31. document.getElementById("btn1").onclick = () =>{
  32. axios
  33. .post("students",{name:"二师兄"})
  34. .then((res) => {
  35. console.log(res.data);
  36. })
  37. .catch((err) => {
  38. console.log("出错了",err);
  39. })
  40. }
  41. </script>
  42. </body>
  43. </html>