123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Axios实例</title>
- <!-- 引入axios -->
- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
- </head>
- <body>
- <button id="btn1">按钮1</button>
- <!-- <button id="btn2">按钮2</button> -->
- <script>
-
- axios.defaults.baseURL = "http://localhost:3000"
- axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem("token")}`;
-
- //axios实例相当于axios的一个副本,它的功能和axios一样
- //axios的默认配置在实例也同样会生效
- //但是我们可以在单独修改axios实例的默认配置,实例默认配置的修改,只对当前实例有效
- //对其他实例和axios无效
- // const instance = axios.create({
- // baseURL:"http://localhost:4000"
- // })
- //或者采用下面的方式进行修改
- const instance = axios.create()
- instance.defaults.baseURL = "http://localhost:4000"
- document.getElementById("btn1").onclick = () =>{
- instance.get("students")
- .then((res) => {
- console.log(res.data);
- })
- .catch((err) => {
- console.log("出错了",err);
- })
- }
- </script>
-
- </body>
- </html>
|