天天看點

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)
  })
           
axios的了解和使用

<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>
           

繼續閱讀