Axios


大部分內容出自《axios官方文檔》

什么是Axios?

Axios是一個基於promise的HTTP庫,可以用在瀏覽器和node.js中。

Axios並不止適用於Vue,還可適用於其他項目中。

Axios的安裝

1.npm安裝: 

npm install axios

執行命令后,在package.json中(這里以Vue項目為例)出現"axios":"版本號",則表示安裝成功。給Vue量身定制的東西才需要在Vue中注冊,例路由router,而axios非給Vue量身定制,在其他地方也能用,實質只是一個普通的插件。

2.使用cdn引入:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

使用axios之前:

當然要先引入axios。

可以在組件(.vue)中引入:

import axios from 'axios'

也可以在main.js中引入並定義實例property:

import axios from 'axios'
Vue.prototype.$axios = axios

如果需要在很多組件里用到某個數據/實用工具,但是不想污染全局作用域時,可以通過在原型上定義它們(Vue.prototype.$appName=''),使其在每個Vue的實例中可用。更多詳細信息訪問添加實例property

使用axios進行請求(以第二種axios引入方式為例):

1.向axios傳遞配置來創建請求

注:在請求過程中很有可能遇到跨域問題(發生在客戶端與服務器之間),解決方案在:這里

① get請求

Ⅰ 第一種寫法

this.$axios('/recipe/byclass', {
      params: {
        appkey: '6d62515547e6f191',
        classid: 2,
        start: 0,
        num: 10
      }
    }).then(function (response) {
      console.log(response)
    })

Ⅱ 第二種寫法

this.$axios({
      method: 'get',
      url: '/recipe/byclass',
      params: {
        appkey: '6d62515547e6f191',
        classid: 2,
        start: 0,
        num: 10
      }
    }).then(function (response) {
      console.log(response.data)
    })

② post請求

this.$axios({
      method: 'post',
      url: '/recipe/byclass',
      data: {
        appkey: '6d62515547e6f191',
        classid: 2,
        start: 0,
        num: 10
      },
      header:{
        'Content-Type':'application/x-www-form-urlencoded'
      }
    }).then(function (response) {
      console.log(response.data)
    })

2.請求方法的別名(axios API)

為方便起見,為所有支持的請求方法提供了別名。

this.$axios.request({config})
this.$axios.get('url',{config})//{config}可選
this.$axios.delete('url',{config})//{config}可選
this.$axios.head('url',{config})//{config}可選
this.$axios.post('url',{data},{config})//{data}、{config}可選
this.$axios.put('url',{data},{config})//{data}、{config}可選
this.$axios.patch('url',{data},{config})//{data}、{config}可選

使用方式舉例:

get()

this.$axios.get('/recipe/byclass', {
      params: {
        classid: '2',
        start: 0,
        num: 10,
        appkey: '6d62515547e6f191'
      }
    }).then(function (response) {
      console.log(response)
    }).catch(function (error) {
      console.log(error)
    })

對於get請求來說,第二個參數({params})非必須,且第一個參數可以寫成'地址?key=value&key1=value1'形式。

axios.get()結果是一個Promise,所以可以繼續鏈式調用.then(()=>{})(請求成功后的回調函數)和.catch(()=>{})(請求失敗后的回調函數)。

post()

this.$axios.post('/recipe/byclass', {
      appkey: '6d62515547e6f191',
      classid: 2,
      start: 0,
      num: 10
    }, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }).then(function (response) {
      console.log(response)
    }).catch(function (error) {
      console.log(error)
    })

使用自定義配置創建axios實例:

var instance = this.$axios.create({
      baseURL:'/recipe',//如果使用了請求代理,這里就不需要寫整個url
      timeout:1000,//請求若超時,則取消請求
      headers:{
        'X-Custom-Header':'foobar'
      }
    })

創建的實例配置將和7個axios API中指定的配置合並。

axios請求配置:

1.局部請求配置

創建請求時可以用的配置選項(設置在axios實例配置或者axios API指定配置中都可以,因為最后都會合並到一起):

屬性 含義
url(必須) 用於請求服務器的URL
method

創建請求時使用的方法,默認為get

baseURL

將自動加在url前面,除非url是一個絕對URL

可以通過設置baseURL,便於為axios實例的方法傳遞相對URL

transformRequest

是一個數組,數組項是一個函數,該函數必須返回一個字符串或ArrayBuffer或Stream

允許在向服務器發送前,修改請求數據

只能用在PUT、POST、PATCH這幾個請求方法

transformResponse

是一個數組,數組項是一個函數,該函數必須返回一個字符串或ArrayBuffer或Stream

在傳遞給then/catch前,允許修改響應數據

headers

即將被發送的自定義請求頭

例:{'Content-Type':'application/json'}

params

即將與請求一起發送的URL參數

必須是一個無格式對象(plain object)或URLSearchParams對象

paramsSerializer

是一個負責params序列化的函數

data

作為請求體被發送的數據

只適用於PUT、POST、PATCH這些請求方法

在沒有設置transformRequest時,data必須是以下類型之一:

string、plain object、ArrayBuffer、ArrayBufferView、URLSearchParams

瀏覽器專屬:FormData、File、Blob

Node專屬:Stream

timeout

指定請求超時的毫秒數(0 表示無超時時間)

若請求花費了超過timeout時間,請求將被中斷

withCredentials

默認值為false

表示跨域請求時是否需要使用憑證

adapter

是一個函數,允許自定義處理請求,以使測試更輕松

返回一個promise並應用一個有效響應

auth

表示應該使用HTTP基礎驗證,並提供憑據

這將設置一個Authorization頭,覆寫掉現有的任意使用headers設置的自定義Authorization頭

responseType

表示服務器響應的數據類型,可以是ArrayBuffer、Blob、Document、JSON、Text、Stream

默認格式為JSON

xsrfCookieName

用作xsrf token的值的cookie的名稱

默認值為XSRF-TOKEN

(csrf/xsrf 跨站請求偽造。一般是攻擊者冒充用戶進行站內操作,與XSS非常不同,XSS利用站點內的信任用戶,而XSRF是偽裝成受信任用戶的請求來訪問操作受信任的網站。詳細信息可查看這里)

xsrfHeaderName

承載xsrf token的值的HTTP頭的名稱

默認值為X-XSRF-TOKEN

onUploadProgress

是一個函數

允許為上傳 處理進度事件

onDownloadProgress

是一個函數

允許為下載 處理進度事件

maxContentLength

定義允許的相應內容的最大尺寸

validateStates

是一個函數

定義對於給定HTTP響應狀態碼是resolve或reject promise

如果validateStatus返回true或設置為null或undefined,promise將被resolve,否則promise將被reject

默認值return status>=200&& status<300

maxRedirects

定義在node.js中follow的最大重定向數目

默認值為5

若設置為0,將不會follow任何重定向

httpAgent

httpsAgent

分別在node.js中用於定義在執行http和https時使用的自定義代理

例:http(s)Agent:new http(s).Agent({keepAlive:true})

keepAlive默認沒有啟用(false)

proxy

定義代理服務器的主機名稱和端口

auth表示HTTP基礎驗證應當用於連接代理,並提供憑據

將會設置一個Proxy-Authoriazation頭,覆寫掉已有的通過使用header設置的自定義Proxy-Authorization頭

cancelToken

用於取消請求的cancel token

例:cancelToken:new CancelToken(function (cancel{}))

{
      url: '',
      method: 'get',
      baseURL: '',
      transformRequest: [function (data) {
        return data;
      }],
      transformResponse: [function (data) {
        return data;
      }],
      headers: {
        'Content-Type': 'application/json'
      },
      params: {
        name: '小紅'
      },
      paramsSerializer: function (params) {
        return Qs.stringify(params, {arrayFormat: 'brackets'})
      },
      data: {
        classid: 1
      },
      timeout: 1000,
      withCredentials: false,
      adapter: function (config) {
      },
      auth: {
        username: 'xxx',
        password: 'xxx'
      },
      responseType: 'json',
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      onUploadProgress: function (progressEvent) {
      },
      onDownloadProgress: function (progressEvent) {
      },
      maxContentLength: 2000,
      validateStates: function (status) {
        return status >= 200 && status < 300;
      },
      maxRediects: 5,
      httpAgent: new http.Agent({keepAlive: true}),
      httpsAgent: new http.Agent({keepAlive: true}),
      proxy: {
        host: '127.0.0.1',
        port: 9000,
        auth: {
          username: 'xxx',
          password: 'xxx'
        }
      },
      cancelToken: new CancelToken(function (cancel) {
      })
    }

2.全局axios配置

this.$axios.defaults.baseURL = 'xxx'
this.$axios.headers.common['Authorization'] = 'xxx'
this.$axios.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

3.在axios實例創建后修改默認值

var instance = this.$axios.create({
    baseURL: 'xxx'
});
instance.defaults.headers.common['Authorization'] = 'xxx'

4.配置優先順序

配置會以一個優先順序進行合並(后者覆蓋前者)。

① 在lib/defaults.js找到的庫的默認值

//使用由庫提供的配置默認值來創建實例
var instance = this.$axios.create();

② 實例的defaults屬性

instance.defaults.timeout = 2500;

③ 請求的config參數

instance.get('/recipe/byclass',{
  timeout:5000
});

攔截器:

在請求或響應被then或catch處理前攔截它們。

1.添加攔截器

① 請求攔截(所有請求處理前被攔截)

this.$axios.interceptors.request.use(function (config) {
    /*在發送請求前對配置做處理
    * 對所有請求都生效*/
    return config;//必須寫,否則配置不生效
}, function (error) {
    return Promise.reject(error);
})

② 響應攔截(所有數據返回后被攔截)

this.$axios.interceptors.response.use(function (response) {
    /*對響應的數據做處理*/
    /*axios獲取返回結果:.then(function(response){response.data...}),而如果在這里返回response.data則可以直接使用*/
    return response;
}, function (error) {
    return Promise.reject(error);
})

③ 為自定義axios實例添加攔截器(請求攔截為例)

var instance = this.$axios.create();
instance.interceptors.request.use(function(){});

2.刪除攔截器(請求攔截為例)

var myInterceptor = this.$axios.interceptors.request.use(function () {
});
this.$axios.interceptors.request.eject(myInterceptor);

錯誤處理:

this.$axios.get('xxx', {
    /*【可選】可以使用validateStatus選項定義一個自定義HTTP狀態碼的錯誤范圍,在錯誤范圍時會進入.catch()*/
    validateStatus: function (status) {
        return status < 500;//status>=500時才會reject
    }
}).then(function (response) {
}).catch(function (error) {
    if (error.response) {
        console.log(error.response.data);
    } else {
        console.log('Error', error.message);
    }
    console.log(error.config);
})

取消:

使用cancel token取消請求。可以使用同一cancel token取消多個請求。

1.使用CancelToken.source工廠方法創建cancel token

var CancelToken = this.$axios.CancelToken;
var source = CancelToken.source();
this.$axios.get('xxx',{
    /*將cancel token和請求綁定,以便以后取消*/
    cancelToken:source.token
}).catch(function (thrown){
    if (this.$axios.isCancel(thrown)){
        console.log('Request canceled',thrown.message);
    } else{
        //處理錯誤
    }
});
/*取消請求  message參數可選*/
source.cancel('message');

2.傳遞executor函數到CancelToken的構造函數創建cancel token

var CancelToken = this.$axios.CancelToken;
var cancel;
this.$axios.get('xxx', {
    /*CancelToken構造函數接收一個executor函數,該函數接收一個cancel函數(取消請求操作)作為參數,也就是c*/
    cancelToken: new CancelToken(function executor(c) {
        cancel = c;
    })
});
/*取消請求(調用cancel函數)*/
cancel();


免責聲明!

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



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