---
# System prepended metadata

title: axios
tags: [axios]

---

---
tags: axios
---
# axios
## ajax缺點
異步請求
接收數據採用回調函數
1.jQuery庫龐大，佔用內存多
2.多個異步請求會產生回調地獄問題
## axios特點
1-1.可運行在node.js
1-2.可運行在瀏覽器端
2.基於promise網路請求庫，能解決回調地獄
3.axios可以用在vue和react
4.佔用內存小
## json-server
官網
https://www.npmjs.com/package/json-server
`npm install -g json-server`
`json-server -v`
`json-server`
自己寫數據
```json=
{
  "student":[
    {"id":"1001","name":"小明","age":20},
    {"id":"1002","name":"小華","age":18},
    {"id":"1003","name":"小美","age":18},
    {"id":"1004","name":"小靜","age":40}
  ]
}
```
若會報錯的話需要額外使用開啟權限
`json-server --watch data.json`
改變端口號寫法
`json-server --watch data.json --port 80`
### Restful API
get:表示檢索
檢索全部`http://localhost:3000/student`
通過ID檢索`http://localhost:3000/student/1001`
通過條件檢索(可能有多項結果)`http://localhost:3000/student?age=18`
![](https://hackmd.io/_uploads/BkIvoFDLh.png)
![](https://hackmd.io/_uploads/ryPbnYv83.png)
![](https://hackmd.io/_uploads/HJKR2YPU2.png)
put:字段重組，id順序錯亂，age(沒寫到的屬性)通通消失
![](https://hackmd.io/_uploads/rykBx9wI3.png)


### 開啟權限
在終端機執行
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
### 關聯數據
```json=
{
  "student": [
    {
      "id": "1001",
      "name": "小明改",
      "age": 20,
      "classId":"1"
    },
    {
      "name": "小華改",
      "id": "1002",
      "classId":"1"
    },
    {
      "id": "1003",
      "name": "小美",
      "age": 18,
      "classId":"1"
    },
    {
      "id": "1004",
      "name": "小靜",
      "age": 40,
      "classId":"2"
    }
  ],
  "classes":[
    {
      "id":"1",
      "title":"web班",
      "studentId":["1001","1002","1003"]
    },
    {
      "id":"2",
      "title":"java班",
      "studentId":["1004"]
    }
  ]
}
```
![](https://hackmd.io/_uploads/HyBGQAdIn.png)
![](https://hackmd.io/_uploads/HJkEN0dU3.png)
## 開始使用
官網
http://axios-js.com/zh-cn/
開源cdn
https://www.bootcdn.cn/
`<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>`
## get
![](https://hackmd.io/_uploads/H1OiGkt83.png)
```javascript=
<!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>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
  </head>
  <body>
    <button id="getNode">發送get請求</button>
    <button id="postNode">發送post請求</button>
    <button id="deleteNode">發送delete請求</button>
    <button id="putNode">發送put請求</button>
    <button id="patchNode">發送patch請求</button>
    <script>
      console.log(axios);
      console.dir(axios);
      getNode.onclick = function () {
        axios
          .get("http://localhost/student")
          .then((result) => {
            console.log(result);
            const { data } = result; // 獲取服務器端的響應數據
            console.log(data);
          })
          .catch((err) => {
            console.log(err);
          });
      };
    </script>
  </body>
</html>
```
```javascript=
        axios
          .get("http://localhost/student/1001")
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
```
```javascript=
        axios
          .get("http://localhost/student?age=18")
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
```
```javascript=
        axios
          .get("http://localhost/student", {
            params: {
              age: 18
            }
          })
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
```
## post
```javascript=
      postNode.onclick = function () {
        axios
          .post("http://localhost/student", {
            id: "1005",
            name: "小紅"
          })
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
      };
```
## delete
```javascript=
      deleteNode.onclick = function () {
        axios
          .delete("http://localhost/student/1005")
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
      };
```
## put
```javascript=
      putNode.onclick = function () {
        axios
          .put("http://localhost/student/1002", {
            name: "小華",
          })
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
      };
```
## patch
```javascript=
      patchNode.onclick = function () {
        axios
          .patch("http://localhost/student/1001", {
            name: "小明明",
          })
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
      };
```
# 阿賈克斯
```javascript=
<!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>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
  </head>
  <body>
    <button id="sendRequestNode">發送請求</button>
    <script>
      sendRequestNode.onclick = function () {
        axios({
          // 配置請求的url
          url: "/student",
          params: {
            age: 18,
          },
          // 配置請求類型 默認get
          method: "get",
          // 基礎路徑 請求路徑 = 基礎路徑[協議,IP,端口] + 項目路徑
          baseURL: "http://localhost",
        })
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
      };
    </script>
  </body>
</html>
```
```javascript=
      sendRequestPostNode.onclick = function () {
        axios({
          url: "/student",
          method: "post",
          baseURL: "http://localhost",
          data:{
            id:"1005",
            name:"小強",
            age:19,
            classId:1
          }
        })
          .then((result) => {
            console.log(result);
            console.log("添加成功");
          })
          .catch((err) => {
            console.log(err);
          });
      };
```
## 請求過濾
```javascript=
      sendRequestFilterNode.onclick = function () {
        axios({
          url: "/student",
          method: "post",
          baseURL: "http://localhost",
          data: {
            id: "1005",
            name: "小強",
            age: 19,
            classId: 1,
          },
          // 大小寫要注意
          transformRequest: [
            function (data, headers) {
              data.name = "小明";
              let params = "";
              for (const [key, value] of Object.entries(data)) {
                params += `${key}=${value}&`;
              }
              if (params) {
                params = params.substring(0, params.length - 1);
              }
              return params;
            },
          ],
        })
          .then((result) => {
            console.log(result);
            console.log("添加成功");
          })
          .catch((err) => {
            console.log(err);
          });
      };
```
## 響應過濾
```javascript=
      sendResponseFilterNode.onclick = function () {
        axios({
          url: "/student",
          params: {
            age: 18,
          },
          method: "get",
          baseURL: "http://localhost",
          transformResponse:[function(data){
            // data響應回來是字符串
            console.log("####",data);
            const dataObj =JSON.parse(data)
            dataObj[0].name='小綠'
            return dataObj
          }]
        })
          .then((result) => {
            console.log("xxxx",result.data);
          })
          .catch((err) => {
            console.log(err);
          });
      };
```
## 請求頭
範例網站
https://m.maizuo.com/v5/?co=mzmovie#/films/comingSoon
![](https://hackmd.io/_uploads/HJaDkPi82.png)
請求頭不可多不可少
![](https://hackmd.io/_uploads/SkCfquoIh.png)

![](https://hackmd.io/_uploads/ryQ5KdoUh.png)
### 請求頭懶人解法
安裝chrome插件
https://seanacnet.com/website-related/cors-error-chrome-easy-cors/
# 全局配置
`axios.defaults.baseURL = "http://localhost"`
```javascript=
<!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>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
  </head>
  <body>
    <button id="addNode">新增</button>
    <button id="findNode">檢索</button>
    <script>
      // 全局配置
      axios.defaults.baseURL = "http://localhost";
      addNode.onclick = function () {
        axios({
          url: "/student",
          method: "post",
          data: {
            id: "1005",
            name: "小強",
            age: 19,
            classId: 1,
          },
        })
          .then((result) => {
            console.log(result);
            console.log("添加成功");
          })
          .catch((err) => {
            console.log(err);
          });
      };
      findNode.onclick = function () {
        axios({
          url: "/student",
          params: {
            age: 18,
          },
          method: "get",
        })
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
      };
    </script>
  </body>
</html>
```
# 攔截器
![](https://hackmd.io/_uploads/Sk-W-JaLh.png)
```javascript=
<!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>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
  </head>
  <body>
    <button id="requestNode">請求攔截器</button>
    <button id="responseNode">響應攔截器</button>
    <script>
      axios.interceptors.request.use(
        function (config) {
          console.log(config);
          // config.data直接是一個對象
          config.data.name && (config.data.name = "小明");
          return config;
        },
        function (error) {
          return Promise.reject(error);
        }
      );
      requestNode.onclick = function () {
        axios({
          url: "/student",
          method: "post",
          baseURL: "http://localhost",
          data: {
            id: "1005",
            name: "小強",
            age: 19,
            classId: 1,
          },
        })
          .then((result) => {
            console.log(result);
            console.log("添加成功");
          })
          .catch((err) => {
            console.log(err);
          });
      };
      responseNode.onclick = function () {
        axios({
          url: "/student",
          params: {
            age: 18,
          },
          method: "get",
          baseURL: "http://localhost",
        })
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
      };
    </script>
  </body>
</html>
```
```javascript=
<!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>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
  </head>
  <body>
    <button id="requestNode">請求攔截器</button>
    <button id="responseNode">響應攔截器</button>
    <script>
      axios.interceptors.response.use(
        function (response) {
          // 对响应数据做点什么
          console.log(response);
          response.data[0].name = "小綠";
          return response;
        },
        function (error) {
          // 对响应错误做点什么
          return Promise.reject(error);
        }
      );
      requestNode.onclick = function () {
        axios({
          url: "/student",
          method: "post",
          baseURL: "http://localhost",
          data: {
            id: "1005",
            name: "小強",
            age: 19,
            classId: 1,
          },
        })
          .then((result) => {
            console.log(result);
            console.log("添加成功");
          })
          .catch((err) => {
            console.log(err);
          });
      };
      responseNode.onclick = function () {
        axios({
          url: "/student",
          params: {
            age: 18,
          },
          method: "get",
          baseURL: "http://localhost",
        })
          .then((result) => {
            console.log(result);
          })
          .catch((err) => {
            console.log(err);
          });
      };
    </script>
  </body>
</html>
```