axios詳解

vuejs 2 後 做者尤雨溪發佈消息,再也不繼續維護vue-resource,官方推薦大axios。javascript

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

特性:css

從瀏覽器中建立 XMLHttpRequestshtml

從 node.js 建立 http 請求vue

支持 Promise APIjava

攔截請求和響應node

轉換請求數據和響應數據jquery

取消請求webpack

自動轉換 JSON 數據ios

客戶端支持防護 XSRF

1、安裝:

一、 利用npm安裝npm install axios --save

二、 利用bower安裝bower install axios --save

三、 直接利用cdn引入<script src="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script>

2、使用:

假如你安裝了vue腳手架,則在main.js文件中添加以下代碼:

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

而後在組件中能夠這樣使用了:

<script> export default { data() { return { visible: false }; }, methods: { getData() { this.$axios.get("https://api.github.com/events") .then(function (response) { console.log(response) }) .catch(function (error) { console.log(error); }) } } }; </script>

 說明:

安裝其餘插件的時候,能夠直接在 main.js 中引入並使用 Vue.use()來註冊,可是 axios並非vue插件,因此不能使用Vue.use(),因此只能在每一個須要發送請求的組件中即時引入。

爲了解決這個問題,咱們在引入 axios 以後,經過修改原型鏈,來更方便的使用。

3、發起POST請求:

axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });

4、發起一個GET請求:

axios.get('https://api.github.com/events')
        .then(function(response){
            console.log(response.data);
        })
        .catch(function(err){
            console.log(err);
        });

攜帶參數:

// 向具備指定ID的用戶發出請求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

 或

// 也能夠經過 params 對象傳遞參數
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

5、併發請求:一次發起多個請求

處理併發請求的助手函數

axios.all( iterable )
axios.spread( callback )
function getUserAccount() {
  return axios.get('/user/12345');
}
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));
//兩個請求同時請求成功才返回數據
axios.all([http1(),http2()]).then( (response)=>{
        console.log(response);  //返回的是一個數組,數組項是每一個請求返回的結果,用下標去取每一個請求的結果
        } )

        axios.all([http1(),http2()]).then(axios.spread((res1,res2)=>{ //用spread分割開2個請求返回的結果
                console.log(res1)  //第一個請求返回的結果
                console.log(res2) //第二個請求返回的結果
        }))
        .catch((error) =>{
            if (axios.isCancel(error)) {
                console.log(error.message);
            }else{
                    console.log(error)
            }
})

6、axios能夠經過配置(config)來發送請求:

// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// GET request for remote image
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

axios(url[, config])

// Send a GET request (default method)
axios('/user/12345');

請求方法的別名

爲方便起見,爲全部支持的請求方法提供了別名

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

NOTE

在使用別名方法時, url、method、data 這些屬性都沒必要在配置中指定。

7、當有跨域限制的時候解決方案:

跨域的解決辦法有不少,好比script標籤 、jsonp、後端設置cros等等...,可是我這裏講的是webpack配置vue 的 proxyTable解決跨域。

這裏我請求的地址是 http://www.thenewstep.cn/test/testToken.php

那麼在ProxyTable中具體配置以下:

proxyTable: {
      '/apis': { // 測試環境 target: 'http://www.thenewstep.cn/', // 接口域名 changeOrigin: true, //是否跨域 pathRewrite: { '^/apis': '' //須要rewrite重寫的, } }

target:就是須要請求地址的接口域名。 

這裏列舉了1種數據請求方式:axios

main.js代碼:

import Vue from 'vue' import App from './App' import axios from 'axios' Vue.config.productionTip = false Vue.prototype.$axios = axios //將axios掛載在Vue實例原型上 // 設置axios請求的token axios.defaults.headers.common['token'] = 'f4c902c9ae5a2a9d8f84868ad064e706' //設置請求頭 axios.defaults.headers.post["Content-type"] = "application/json"

axios請求頁面代碼:

this.$axios.post('/apis/test/testToken.php',data).then(res=>{ console.log(res) })

這裏的'apis'就是在ProxyTable中配置的'/apis'。

8、建立實例:

可使用自定義配置新建一個 axios 實例

axios.create([config])

var instance = axios.create({ baseURL:'', timeout:1000, headers:{}, responseType:'json', params:{}, transformRequest:[], 只適合PUT、POST和、PATCH transformResponse:[], validateStatus:function(){}, //驗證狀態碼在哪一個範圍是成功,哪一個範圍是失敗 cancelToken });

實例:http組件

import axios from 'axios';
import queryString from 'queryString'

//建立取消請求令牌
var CancelToken = axios.CancelToken;
var source = CancelToken.source();

//能夠把這個HTTP寫在某一個單獨的組件內,也能夠提取出來放在一個js文件內,
//而後export default HTTP,在其餘組件內,經過import這個js文件進行使用
var HTTP = axios.create({
    baseURL:'https://www.easy-mock.com/mock/5c1767c06ccaa7461ef01ee9/example/'   //基本url都同樣
    timeout:1000        //單位是ms,請求超過這個時間就取消,即請求超時
    responseType:'json',  //後端返回的數據類型
    header:{  //自定義請求頭
        'custom-header':'xiao',  //Request Headers裏面就多了一個custom-header:xiao,後端能夠拿到這個數據
        'content-type':'application/x-www-form-urlencoded'  //設置這個,那麼通過transformRequest處理以後的數據格式就變爲了  miaov=ketang&username=leo,只支持POST請求方式
    },
    params:{  //查詢字符串,傳給後端的數據,不論是get仍是post請求,這條數據都會附在url後面,發送給後端
        bookId:'123'
    },
    transformRequest:[function(data){  //數組格式,用於轉換髮送數據格式,只適合PUT、POST、PATCH,data是傳遞給後端的數據,transformRequest相似一箇中間件,發送數據,通過它來轉換,須要reture出來,不然就是undefined,可是不能直接是return data,由於這樣返回的是[object object],
安裝queryString來處理查詢字符串,格式化成一個字符串
      data.age = 30;  //發送請求以前能夠再次添加數據
      return queryString.stringify(data);  
    }],
    transformResponse:[function(data){   //數組格式,用於處理返回的數據格式,data是後端發送回來的數據
      data.abc = 'miaov'  //對返回數據作進一步處理,請求此類地址的返回值都擁有abc這個屬性,值是miaov
      return data;  //須要return出來
    }],
    cancelToken: source.token  //主動取消請求
})

export default({
    created(){
      HTTP.get('test-axios')
      .then((response)=>{
            console.log(response.data)
        })
      .catch((error) =>{
        console.log(error)
    })

  }
})

export default{
    created(){
        HTTP.post('postData#!method=post',{   //只是請求方式不同
                miaov:"ketang", 
        username:"leo"
        }) 
        .then( (response)=>{
            console.log(response.data)
        } )
        .catch( (error)=>{
            if (axios.isCancel(error)) {  //被用戶取消
          console.log(error.message);
        }else{  //發送請求超時
            console.log(error)
        }
        } )

        //手動、當即取消請求,走catch分支,添加這個,會走catch裏面的if分支,不添加這個,若是出錯會走else分支
        source.cancel('操做被用戶取消')
    }
}

實例方法

如下是可用的實例方法。指定的配置將與實例的配置合併

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])

請求配置

 這些是建立請求時能夠用的配置選項。只有 url 是必需的。若是沒有指定 method,請求將默認使用 get 方法。

{
  // `url` 是用於請求的服務器 URL url: '/user', // `method` 是建立請求時使用的方法 method: 'get', // 默認是 get // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。 // 它能夠經過設置一個 `baseURL` 便於爲 axios 實例的方法傳遞相對 URL baseURL: 'https://some-domain.com/api/', // `transformRequest` 容許在向服務器發送前,修改請求數據 // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法 // 後面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data) { // 對 data 進行任意轉換處理 return data; }], // `transformResponse` 在傳遞給 then/catch 前,容許修改響應數據 transformResponse: [function (data) { // 對 data 進行任意轉換處理 return data; }], // `headers` 是即將被髮送的自定義請求頭 headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` 是即將與請求一塊兒發送的 URL 參數 // 必須是一個無格式對象(plain object)或 URLSearchParams 對象 params: { ID: 12345 }, // `paramsSerializer` 是一個負責 `params` 序列化的函數 // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` 是做爲請求主體被髮送的數據 // 只適用於這些請求方法 'PUT', 'POST', 和 'PATCH' // 在沒有設置 `transformRequest` 時,必須是如下類型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 瀏覽器專屬:FormData, File, Blob // - Node 專屬: Stream data: { firstName: 'Fred' }, // `timeout` 指定請求超時的毫秒數(0 表示無超時時間) // 若是請求話費了超過 `timeout` 的時間,請求將被中斷 timeout: 1000, // `withCredentials` 表示跨域請求時是否須要使用憑證 withCredentials: false, // 默認的 // `adapter` 容許自定義處理請求,以使測試更輕鬆 // 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)). adapter: function (config) { /* ... */ }, // `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據 // 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭 auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` 表示服務器響應的數據類型,能夠是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // 默認的 // `xsrfCookieName` 是用做 xsrf token 的值的cookie的名稱 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱 xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的 // `onUploadProgress` 容許爲上傳處理進度事件 onUploadProgress: function (progressEvent) { // 對原生進度事件的處理 }, // `onDownloadProgress` 容許爲下載處理進度事件 onDownloadProgress: function (progressEvent) { // 對原生進度事件的處理 }, // `maxContentLength` 定義容許的響應內容的最大尺寸 maxContentLength: 2000, // `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。若是 `validateStatus` 返回 `true` (或者設置爲 `null` 或 `undefined`),promise 將被 resolve; 不然,promise 將被 rejecte validateStatus: function (status) { return status >= 200 && status < 300; // 默認的 }, // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目 // 若是設置爲0,將不會 follow 任何重定向 maxRedirects: 5, // 默認的 // `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 http 和 https 時使用的自定義代理。容許像這樣配置選項: // `keepAlive` 默認沒有啓用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' 定義代理服務器的主機名稱和端口 // `auth` 表示 HTTP 基礎驗證應當用於鏈接代理,並提供憑據 // 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的經過使用 `header` 設置的自定義 `Proxy-Authorization` 頭。 proxy: { host: '127.0.0.1', port: 9000, auth: : { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` 指定用於取消請求的 cancel token // (查看後面的 Cancellation 這節瞭解更多) cancelToken: new CancelToken(function (cancel) { }) }

響應結構

某個請求的響應包含如下信息

{
  // `data` 由服務器提供的響應 data: {}, // `status` 來自服務器響應的 HTTP 狀態碼 status: 200, // `statusText` 來自服務器響應的 HTTP 狀態信息 statusText: 'OK', // `headers` 服務器響應的頭 headers: {}, // `config` 是爲請求提供的配置信息 config: {} }

 使用 then 時,你將接收下面這樣的響應:

axios.get('/user/12345') .then(function(response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); });

在使用 catch 時,或傳遞 rejection callback 做爲 then 的第二個參數時,響應能夠經過 error 對象可被使用,正如在錯誤處理這一節所講。

配置的默認值/defaults

你能夠指定將被用在各個請求的配置默認值

全局的 axios 默認值

axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

自定義實例默認值

// 建立實例時設置配置的默認值 var instance = axios.create({ baseURL: 'https://api.example.com' }); // 在實例已建立後修改默認值 instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

 配置的優先順序

配置會以一個優先順序進行合併。這個順序是:在 lib/defaults.js 找到的庫的默認值,而後是實例的 defaults 屬性,最後是請求的 config 參數。後者將優先於前者。這裏是一個例子:

// 使用由庫提供的配置的默認值來建立實例 // 此時超時配置的默認值是 `0` var instance = axios.create(); // 覆寫庫的超時默認值 // 如今,在超時前,全部請求都會等待 2.5 秒 instance.defaults.timeout = 2500; // 爲已知須要花費很長時間的請求覆寫超時設置 instance.get('/longRequest', { timeout: 5000 });

9、攔截器:

一、發送以前能夠對請求進行攔截,還能夠攔截響應,相似中間件。你能夠在請求、響應在到達then/catch以前攔截他們。

var HTTP = axios.create({  //自定義請求
    baseURL:'http://easy-mock.com/mock/596077559adc231f357bcdfb/axios/',
    timeout: 1000,
    responseType:'json',
    headers:{
        'custome-header': 'miaov',
        'content-type':'application/x-www-form-urlencoded'
    }
})

//添加一個請求攔截器:請求以前的攔截
HTTP.interceptors.request.use(function(config){  //config就是自定義請求的配置信息,即HTTP的配置參數
    //在發送請求以前作某事
    console.log("攔截")
    //這裏能夠對配置項config作處理,取消某些配置或增長
    return config;  //return config請求會繼續進行,不然請求就被攔截了
},function(error){
    //請求錯誤時作些事
    return Promise.reject(error);
});

//添加一個請求攔截器:請求以後的攔截
HTTP.interceptors.response.use(function(data){
        console.log("response")
        console.log(data)
        return data;  //須要return data才能拿到數據,不然就是undefined
})

二、取消攔截器:

var myInterceptor = axios.interceptor.request.use(function(){/*....*/});
axios.interceptors.request.eject(myInterceptor);

三、 給自定義的axios實例添加攔截器:

var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

10、錯誤處理:

axios.get('/user/12345') .catch(function (error) { if (error.response) { // 請求已發出,但服務器響應的狀態碼不在 2xx 範圍內 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); });

可使用 validateStatus 配置選項定義一個自定義 HTTP 狀態碼的錯誤範圍。

axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // 狀態碼在大於或等於500時纔會 reject } })

11、取消

使用 cancel token 取消請求

Axios 的 cancel token API 基於cancelable promises proposal,它還處於第一階段。

可使用 CancelToken.source 工廠方法建立 cancel token,像這樣:

var CancelToken = axios.CancelToken; var source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // 處理錯誤 } }); // 取消請求(message 參數是可選的) source.cancel('Operation canceled by the user.');

還能夠經過傳遞一個 executor 函數到 CancelToken 的構造函數來建立 cancel token:

var CancelToken = axios.CancelToken; var cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // executor 函數接收一個 cancel 函數做爲參數 cancel = c; }) }); // 取消請求 cancel();

Note : 可使用同一個 cancel token 取消多個請求

11、將axios定義在一個單獨的文件中:

http.js

import axios from 'axios';

let HTTP = axios.create({
  baseURL:'http://127.0.0.1:8000/',
  timeout:1000,        //單位是ms,請求超過這個時間就取消,即請求超時
  responseType:'json',  //後端返回的數據類型
  header:{  //自定義請求頭
    'custom-header':'xiao',  //Request Headers裏面就多了一個custom-header:xiao,後端能夠拿到這個數據
    'content-type':'application/x-www-form-urlencoded'  //設置這個,那麼通過transformRequest處理以後的數據格式就變爲了  miaov=ketang&username=leo,只支持POST請求方式
  },
  params:{  //查詢字符串,傳給後端的數據,不論是get仍是post請求,這條數據都會附在url後面,發送給後端
    bookId:'123'
  },
  transformResponse:[function(data){   //數組格式,用於處理返回的數據格式,data是後端發送回來的數據
    data.abc = 'miaov'  //對返回數據作進一步處理,請求此類地址的返回值都擁有abc這個屬性,值是miaov
    return data;  //須要return出來
  }]
});

//添加一個請求攔截器:請求以前的攔截
HTTP.interceptors.request.use(function(config){  //config就是自定義請求的配置信息,即HTTP的配置參數
  //在發送請求以前作某事
  console.log("攔截")
  //這裏能夠對配置項config作處理,取消某些配置或增長
  return config;  //return config請求會繼續進行,不然請求就被攔截了
},function(error){
  //請求錯誤時作些事
  return Promise.reject(error);
});

//添加一個請求攔截器:請求以後的攔截
HTTP.interceptors.response.use(function(data){
  console.log("response")
  console.log(data)
  return data;  //須要return data才能拿到數據,不然就是undefined
})

export default HTTP;

在main.js中引入http,並修改原型鏈方便使用(同上面的第二大點)

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

import http from './axios/http'
Vue.prototype.$HTTP = http;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

這樣,就能夠在任何地方使用了:

Table.vue

<template>
  <div>
    table
  </div>
</template>

<script>
  export default {
    mounted(){
      this.$HTTP.get('get_data',
        {
          params: {
            id: 12345
          }
        }
      ).then((response)=>{
          console.log(response.data)
        })
        .catch((error) =>{
          console.log(error)
        });
    }
  }
</script>

<style scoped lang="">

</style>
相關文章
相關標籤/搜索