vue2.0項目實戰使用axios發送請求

在Vue1.0的時候有一個官方推薦的 ajax 插件 vue-resource,可是自從 Vue 更新到 2.0 以後,官方就再也不更新 vue-resource。vue

關於爲何放棄推薦? -> 尤大原話node

最近團隊討論了一下,Ajax 自己跟 Vue 並無什麼須要特別整合的地方,使用 fetch polyfill 或是 axios、superagent 等等均可以起到同等的效果,jquery

vue-resource 提供的價值和其維護成本相比並不划算,因此決定在不久之後取消對 vue-resource 的官方推薦。已有的用戶能夠繼續使用,ios

但之後再也不把 vue-resource 做爲官方的 ajax 方案。這裏能夠去掉 vue-resource,文檔也沒必要翻譯了。git

目前主流的 Vue 項目,都選擇 axios 來完成 ajax 請求,下面來具體介紹一下axios的使用。github

axios 簡介

axios 是一個基於Promise 用於瀏覽器和 nodejs 的 HTTP 客戶端,它自己具備如下特徵:ajax

  • 從瀏覽器中建立 XMLHttpRequest
  • 從 node.js 發出 http 請求
  • 支持 Promise API
  • 攔截請求和響應
  • 轉換請求和響應數據
  • 取消請求
  • 自動轉換JSON數據
  • 客戶端支持防止 CSRF/XSRF

引入方式:

$ npm install axios
//使用淘寶源 $ cnpm install axios //或者使用cdn: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

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

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

//main.jsaxios

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

在 main.js 中添加了這兩行代碼以後,就能直接在組件的 methods 中使用 $http命令

methods: {
  postData () {
    this.$http({
      method: 'post',
      url: '/user',
      data: {
        name: 'xiaoming',
        info: '12'
      }
   })
}

下面來介紹axios的具體使用:

執行 GET 請求

// 向具備指定ID的用戶發出請求
$http.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
// 也能夠經過 params 對象傳遞參數
$http.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

執行 POST 請求

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

執行多個併發請求

function getUserAccount() {
  return $http.get('/user/12345');
}
function getUserPermissions() {
  return $http.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
  .then($http.spread(function (acct, perms) {
    //兩個請求現已完成
  }));

axios API

能夠經過將相關配置傳遞給 axios 來進行請求。

axios(config)

複製代碼
// 發送一個 POST 請求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
複製代碼

axios(url[, config])

1
2
// 發送一個 GET 請求 (GET請求是默認請求模式)
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]])

注意
當使用別名方法時,不須要在config中指定url,method和data屬性。

併發

幫助函數處理併發請求。

  • axios.all(iterable)
  • axios.spread(callback)

建立實例

您可使用自定義配置建立axios的新實例。

axios.create([config])

var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

實例方法

可用的實例方法以下所示。 指定的配置將與實例配置合併。

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是必需的。 若是未指定方法,請求將默認爲GET。

複製代碼
{
  // `url`是將用於請求的服務器URL
  url: '/user',
  // `method`是發出請求時使用的請求方法
  method: 'get', // 默認
  // `baseURL`將被添加到`url`前面,除非`url`是絕對的。
  // 能夠方便地爲 axios 的實例設置`baseURL`,以便將相對 URL 傳遞給該實例的方法。
  baseURL: 'https://some-domain.com/api/',
  // `transformRequest`容許在請求數據發送到服務器以前對其進行更改
  // 這隻適用於請求方法'PUT','POST'和'PATCH'
  // 數組中的最後一個函數必須返回一個字符串,一個 ArrayBuffer或一個 Stream
  transformRequest: [function (data) {
    // 作任何你想要的數據轉換
    return data;
  }],
  // `transformResponse`容許在 then / catch以前對響應數據進行更改
  transformResponse: [function (data) {
    // Do whatever you want to transform the data
    return data;
  }],
  // `headers`是要發送的自定義 headers
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  // `params`是要與請求一塊兒發送的URL參數
  // 必須是純對象或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
  // - Browser only: FormData, File, Blob
  // - Node only: Stream
  data: {
    firstName: 'Fred'
  },
  // `timeout`指定請求超時以前的毫秒數。
  // 若是請求的時間超過'timeout',請求將被停止。
  timeout: 1000,
  // `withCredentials`指示是否跨站點訪問控制請求
  // should be made using credentials
  withCredentials: false, // default
  // `adapter'容許自定義處理請求,這使得測試更容易。
  // 返回一個promise並提供一個有效的響應(參見[response docs](#response-api))
  adapter: function (config) {
    /* ... */
  },
  // `auth'表示應該使用 HTTP 基本認證,並提供憑據。
  // 這將設置一個`Authorization'頭,覆蓋任何現有的`Authorization'自定義頭,使用`headers`設置。
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },
  // 「responseType」表示服務器將響應的數據類型
  // 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default
  //`xsrfCookieName`是要用做 xsrf 令牌的值的cookie的名稱
  xsrfCookieName: 'XSRF-TOKEN', // default
  // `xsrfHeaderName`是攜帶xsrf令牌值的http頭的名稱
  xsrfHeaderName: 'X-XSRF-TOKEN', // default
  // `onUploadProgress`容許處理上傳的進度事件
  onUploadProgress: function (progressEvent) {
    // 使用本地 progress 事件作任何你想要作的
  },
  // `onDownloadProgress`容許處理下載的進度事件
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },
  // `maxContentLength`定義容許的http響應內容的最大大小
  maxContentLength: 2000,
  // `validateStatus`定義是否解析或拒絕給定的promise
  // HTTP響應狀態碼。若是`validateStatus`返回`true`(或被設置爲`null` promise將被解析;不然,promise將被
  // 拒絕。
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },
  // `maxRedirects`定義在node.js中要遵循的重定向的最大數量。
  // 若是設置爲0,則不會遵循重定向。
  maxRedirects: 5, // 默認
  // `httpAgent`和`httpsAgent`用於定義在node.js中分別執行http和https請求時使用的自定義代理。
  // 容許配置相似`keepAlive`的選項,
  // 默認狀況下不啓用。
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),
  // 'proxy'定義代理服務器的主機名和端口
  // `auth`表示HTTP Basic auth應該用於鏈接到代理,並提供credentials。
  // 這將設置一個`Proxy-Authorization` header,覆蓋任何使用`headers`設置的現有的`Proxy-Authorization` 自定義 headers。
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: : {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },
  // 「cancelToken」指定可用於取消請求的取消令牌
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  })
}
複製代碼

使用 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);
  });
複製代碼

配置默認值

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

攔截器

你能夠截取請求或響應在被 then 或者 catch 處理以前

複製代碼
//添加請求攔截器
axios.interceptors.request.use(function(config){
     //在發送請求以前作某事
     return config;
   },function(error){
     //請求錯誤時作些事
     return Promise.reject(error);
   });
 
//添加響應攔截器
axios.interceptors.response.use(function(response){
     //對響應數據作些事
      return response;
   },function(error){
     //請求錯誤時作些事
     return Promise.reject(error);
   });
複製代碼

處理錯誤

複製代碼
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 {
       //在設置觸發錯誤的請求時發生了錯誤
       console.log('Error',error.message);
     }}
     console.log(error.config);
   });
複製代碼

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

axios.get('/ user / 12345',{
   validateStatus:function(status){
     return status < 500; //僅當狀態代碼大於或等於500時拒絕
   }}
})

使用application / x-www-form-urlencoded格式

默認狀況下,axios將JavaScript對象序列化爲JSON。 要以應用程序/ x-www-form-urlencoded格式發送數據,您可使用如下選項之一。

瀏覽器

在瀏覽器中,您可使用URLSearchParams API,以下所示:

var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

請注意,全部瀏覽器都不支持URLSearchParams,可是有一個polyfill可用(確保polyfill全局環境)。

或者,您可使用qs庫對數據進行編碼:

var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });
相關文章
相關標籤/搜索