axios的簡單的使用


Axios 是什么?

Axios 是一個基於 promise 網絡請求庫,作用於node.js 和瀏覽器中。 它是 isomorphic 的(即同一套代碼可以運行在瀏覽器和node.js中)。在服務端它使用原生 node.js http 模塊, 而在客戶端 (瀏覽端) 則使用 XMLHttpRequests。

特性

  • 從瀏覽器創建 XMLHttpRequests
  • 從 node.js 創建 http 請求
  • 支持 Promise API
  • 攔截請求和響應
  • 轉換請求和響應數據
  • 取消請求
  • 自動轉換JSON數據
  • 客戶端支持防御XSRF

基礎用法

引入之后直接使用,不做任何配置

import axios from 'axios';

// 向給定ID的用戶發起請求
axios.get('/user?ID=12345')
  .then((response) => {
    // 處理成功情況
    console.log(response);
  })
  .catch((error) => {
    // 處理錯誤情況
    console.log(error);
  })

常規用法

一般我們在項目中使用都會統一的配置接口的baseUrl,超時時間等等

import axios from 'axios';

const _axios = axios.create({
    baseUrl: 'http://localhost:9333/api',
    timeout: 1000 * 15,
})

配置請求攔截器

在請求攔截器中可以做一些常規配置,比如要給請求頭添加token或附加一些特殊的共有數據等等

_axios.interceptors.request.use(config=>{
    // 添加token
    config.headers.token = 'token';
    // do something
},error=>Promise.reject(error))

配置返回攔截器

在請求攔截器中可以做一些常規配置,比如要給請求頭添加token或附加一些特殊的共有數據等等

_axios.interceptors.response.use(config=>{
    // do something
},error=>{
    // 做一些統一的錯誤處理
    // 401 需要授權
    // 404 接口不存在
    // 405 請求方式不允許,本來接口是get的而你使用了post
    // 等等
})

取消重復請求

在項目中會經常碰到一個按鈕連續多次的快速點擊,這樣就會在極短的時間內請求多次,實際上我們只需要一次返回結果就可以,這個時候就可以取消之前多次的重復提交。

在此我們會用到 axios.CancelToken 這個方法,具體使用方法可以查看文檔

封裝取消請求的方法

class CancelToken {
  constructor() {
    this.store = new Map();
  }
  add (config)  {
      const key = this.getKey(config);
      new axios.CancelToken((cancel) => {
        if (this.store.has(key)) {
            this.remove(config)
        }
        this.store.set(key, cancel);
      });
  }
  remove (config)  {
      const key = this.getKey(config);
    if (this.store.has(key)) {
      let cancel = this.store.get(key);
      cancel(key);
      this.store.delete(key);
    }
  }
  // 根據請求參數獲取唯一的key
  getKey(config){
    const { method, url, params, data } = config;
    return [method, url, params, data].join('-');
  }
}

使用CancelToken方法

const cancelToken = new CancelToken();
// 請求攔截器
axios.interceptors.request.use(config=>{
    cancelToken.add(config);
},error=>Promise.reject(error))

// 接收攔截器
axios.interceptors.response.use(
    response => {
        const config = response.config;
        cancelToken.remove(config)
        Promise.resolve(response)
    },
    error => {
        return Promise.reject(error);
    }
);

至此,axios的常規使用就介紹完了,感謝各位的閱讀。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM