1. 程式人生 > 實用技巧 >axios的理解和使用

axios的理解和使用

axios(兒個煞斯)是什麼?

  1. 前端最流行的ajax請求庫
  2. react/vue 官方都推薦使用axios發ajax請求
  3. 文件:http://www.axios-js.com/zh-cn/docs/

axios特點

  1. 基本promise的非同步ajax請求庫
  2. 瀏覽器端/node端都可以使用
  3. 支援請求/響應攔截器
  4. 支援請求取消
  5. 請求/響應資料轉換
  6. 批量傳送多個請求

axios常用語法

axios(config) 通用/最本質的發任意型別請求的方式
axios(url[,config]) 可以只指定url傳送get請求
axios.request(config) 等同於axios(config)
axios.get(url[,config]) 發get請求
axios.delete(url[.config]) 發delete請求
axios.post(url[,data,config]) 發post請求
axios.put(url[,data,config]) 發put請求
axios.defaults.xxx 請求的預設全域性配置
axios.interceptors.request.use() 新增請求攔截器
axios.interceptors.response.use() 新增響應攔截器
axios.create([config]) 建立一個新的axios(它沒有下面的功能)
axios.Cancel() 用於建立取消請求的錯誤物件
axios.CancelToken() 用於建立取消請求的token物件
axios.isCancel() 是否是一個取消請求的錯誤
axios.all(promises) 用於批量執行多個非同步請求
axios.spread() 用來指定接收所有成功資料的回撥函式方法

難點語法的理解和使用

axios.create(config)

  1. 根據指定配置建立一個新的axios, 也就就每個新axios 都有自己的配置
  2. 新axios 只是沒有取消請求和批量發請求的方法, 其它所有語法都是一致的
  3. 為什麼要設計這個語法?
    (1) 需求: 專案中有部分介面需要的配置與另一部分介面需要的配置不太一
    樣, 如何處理
    (2) 解決: 建立2 個新axios, 每個都有自己特有的配置, 分別應用到不同要
    求的介面請求中

攔截器函式/ajax請求/請求的回撥函式的呼叫順序

  1. 說明: 呼叫axios()並不是立即傳送ajax 請求, 而是需要經歷一個較長的流程
  2. 流程: 請求攔截器2 => 請求攔截器1 => 發ajax 請求=> 響應攔截器1 => 響
    應攔截器2 => 請求的回撥
  3. 注意: 此流程是通過promise 串連起來的, 請求攔截器傳遞的是config, 響應
    攔截器傳遞的是response

取消請求

  1. 基本流程
    配置cancelToken 物件
    快取用於取消請求的cancel 函式
    在後面特定時機呼叫cancel 函式取消請求
    在錯誤回撥中判斷如果error 是cancel, 做相應處理
  2. 實現功能
    點選按鈕, 取消某個正在請求中的請求
    在請求一個介面前, 取消前面一個未完成的請求

axios的使用

傳送axios請求

<body>
  
    <div>
      <button onclick="testGet()">GET請求</button>
      <button onclick="testPost()">POST請求</button>
      <button onclick="testPut()">PUT請求</button>
      <button onclick="testDelete()">DELETE請求</button>
    </div>
  
    <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
    <script>
      // 指定預設配置
      axios.defaults.baseURL = 'http://localhost:3000'

      /* 1. GET請求: 從伺服器端獲取資料*/
      function testGet() {
        // axios.get('/posts?id=1')
        axios({
          url: '/posts',
          params: {
            id: 1
          }
        })
          .then(response => {
            console.log('/posts get', response.data)
          })
      }
  
      /* 2. POST請求: 向伺服器端新增新資料*/
      function testPost() {
        // axios.post('/posts', {"title": "json-server3", "author": "typicode3"})
        axios({
          url: '/posts',
          method: 'post',
          data: {"title": "json-server4", "author": "typicode4"}
        })
          .then(response => {
            console.log('/posts post', response.data)
          })
      }
  
      /* 3. PUT請求: 更新伺服器端已經資料 */
      function testPut() {
        // axios.put('http://localhost:3000/posts/4', {"title": "json-server...", "author": "typicode..."})
        axios({
          url: '/posts/4',
          method: 'put',
          data: {"title": "json-server5", "author": "typicode5"}
        })
          .then(response => {
            console.log('/posts put', response.data)
          })
      }
  
      /* 4. DELETE請求: 刪除伺服器端資料 */
      function testDelete() {
        // axios.delete('http://localhost:3000/posts/4')
        axios({
          url: '/posts/5',
          method: 'delete'
        })
          .then(response => {
            console.log('/posts delete', response.data)
          })
      }
  
    </script>
</body>

create方法

需求: 專案中有部分介面需要的配置與另一部分介面需要的配置不太一樣, 如何處理
解決: 建立2個新axios, 每個都有自己特有的配置, 分別應用到不同要求的介面請求中

<body>
  <!-- 
  1). axios.create(config)
    a. 根據指定配置建立一個新的axios, 也就就每個新axios都有自己的配置
    b. 新axios只是沒有取消請求和批量發請求的方法, 其它所有語法都是一致的
    c. 為什麼要設計這個語法?
      需求: 專案中有部分介面需要的配置與另一部分介面需要的配置不太一樣, 如何處理
      解決: 建立2個新axios, 每個都有自己特有的配置, 分別應用到不同要求的介面請求中
  -->
  <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
  <script>
    axios.defaults.baseURL = 'http://localhost:3000'

    // 使用axios發請求
    axios({
      url: '/posts' // 請求3000
    })

    // axios({
    //   url: '/xxx' // 請求4000
    // })

    const instance = axios.create({
      baseURL: 'http://localhost:4000'
    })

    // 使用instance發請求
    // instance({
    //   url: '/xxx'  // 請求4000
    // })
    instance.get('/xxx')
  </script>
</body>

axios的處理鏈流程

// 新增請求攔截器(回撥函式)
axios.interceptors.request.use(
  config => {
    console.log('request interceptor1 onResolved()')
    return config
  },
  error => {
    console.log('request interceptor1 onRejected()')
    return Promise.reject(error);
  }
)
axios.interceptors.request.use(
  config => {
    console.log('request interceptor2 onResolved()')
    return config
  },
  error => {
    console.log('request interceptor2 onRejected()')
    return Promise.reject(error);
  }
)
// 新增響應攔截器
axios.interceptors.response.use(
  response => {
    console.log('response interceptor1 onResolved()')
    return response
  },
  function (error) {
    console.log('response interceptor1 onRejected()')
    return Promise.reject(error);
  }
)
axios.interceptors.response.use(
  response => {
    console.log('response interceptor2 onResolved()')
    return response
  },
  function (error) {
    console.log('response interceptor2 onRejected()')
    return Promise.reject(error);
  }
)

axios.get('http://localhost:3000/posts')
  .then(response => {
    console.log('data', response.data)
  })
  .catch(error => {
    console.log('error', error.message)
  })

取消請求

<body>
  <button onclick="getProducts1()">獲取商品列表1</button><br>
  <button onclick="getProducts2()">獲取商品列表2</button><br>
  <button onclick="cancelReq()">取消請求</button><br>

  <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
  <script>
    let cancel  // 用於儲存取消請求的函式
    function getProducts1() {
      axios({
        url: 'http://localhost:4000/products1',
        cancelToken: new axios.CancelToken((c) => { // c是用於取消當前請求的函式
          // 儲存取消函式, 用於之後可能需要取消當前請求
          cancel = c
        })
      }).then(
        response => {
          cancel = null
          console.log('請求1成功了', response.data)
        },
        error => {
          cancel = null
          console.log('請求1失敗了', error.message, error)
        }
      )
    }

    function getProducts2() {
      axios({
        url: 'http://localhost:4000/products2'
      }).then(
        response => {
          console.log('請求2成功了', response.data)
        },
        error => {
          cancel = null
          console.log('請求2失敗了', error.message)
        }
      )
    }

    function cancelReq() {
      // alert('取消請求')
      // 執行取消請求的函式
      if (typeof cancel === 'function') {
        cancel('強制取消請求')
      } else {
        console.log('沒有可取消的請求')
      }
    }
  </script>
</body>