vue-resource和axios區別

vue-resource

Vue.js是數據驅動的,這使得我們並不需要直接操作DOM,如果我們不需要使用jQuery的DOM選擇器,就沒有必要引入jQuery。vue-resource是Vue.js的一款插件,它可以通過XMLHttpRequest或JSONP發起請求並處理響應。也就是說,$.ajax能做的事情,vue-resource插件一樣也能做到,而且vue-resource的API更爲簡潔。另外,vue-resource還提供了非常有用的inteceptor功能,使用inteceptor可以在請求前和請求後附加一些行爲,比如使用inteceptor在ajax請求時顯示loading界面。

vue-resource特點

vue-resource插件具有以下特點:

  1. 體積小
    vue-resource非常小巧,在壓縮以後只有大約12KB,服務端啓用gzip壓縮後只有4.5KB大小,這遠比jQuery的體積要小得多。
  2. 支持主流的瀏覽器
    和Vue.js一樣,vue-resource除了不支持IE 9以下的瀏覽器,其他主流的瀏覽器都支持。
  3. 支持Promise API和URI Templates
    Promise是ES6的特性,Promise的中文含義爲“先知”,Promise對象用於異步計算。
    URI Templates表示URI模板,有些類似於ASP.NET MVC的路由模板。
  4. 支持攔截器
    攔截器是全局的,攔截器可以在請求發送前和發送請求後做一些處理。
    攔截器在一些場景下會非常有用,比如請求發送前在headers中設置access_token,或者在請求失敗時,提供共通的處理方式。

vue-resource使用

1、引入vue-resource

<script src="js/vue.js"></script>
<script src="js/vue-resource.js"></script>

2、引入vue-resource後,可以基於全局的Vue對象使用http,也可以基於某個Vue實例使用http。

// 基於全局Vue對象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
 
// 在一個Vue實例內使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

在發送請求後,使用then方法來處理響應結果,then方法有兩個參數,第一個參數是響應成功時的回調函數,第二個參數是響應失敗時的回調函數。
then方法的回調函數也有兩種寫法,第一種是傳統的函數寫法,第二種是更爲簡潔的ES 6的Lambda寫法:

// 傳統寫法
this.$http.get('/someUrl', [options]).then(function(response){
  // 響應成功回調
}, function(response){
  // 響應錯誤回調
});
// Lambda寫法
this.$http.get('/someUrl', [options]).then((response) => {
  // 響應成功回調
}, (response) => {
  // 響應錯誤回調
});

支持的HTTP方法

vue-resource的請求API是按照REST風格設計的,它提供了7種請求API:

get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])

除了jsonp以外,另外6種的API名稱是標準的HTTP方法。當服務端使用REST API時,客戶端的編碼風格和服務端的編碼風格近乎一致,這可以減少前端和後端開發人員的溝通成本。

客戶端請求方法服務端處理方法
this.$http.get(...)Getxxx
this.$http.post(...)Postxxx
this.$http.put(...)Putxxx
this.$http.delete(...)Deletexxx

options對象

參數類型描述
urlstring請求的URL
methodstring請求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法
bodyObject, FormData stringrequest body
paramsObject請求的URL參數對象
headersObjectrequest header
timeoutnumber單位爲毫秒的請求超時時間 (0 表示無超時時間)
beforefunction(request)請求發送前的處理函數,類似於jQuery的beforeSend函數
progressfunction(event)ProgressEvent回調處理函數
credentialsboolean表示跨域請求時是否需要使用憑證
emulateHTTPboolean發送PUT, PATCH, DELETE請求時以HTTP POST的方式發送,並設置請求頭的X-HTTP-Method-Override
emulateJSONboolean將request body以application/x-www-form-urlencoded content type發送

emulateHTTP的作用

如果Web服務器無法處理PUT, PATCH和DELETE這種REST風格的請求,你可以啓用enulateHTTP現象。啓用該選項後,請求會以普通的POST方法發出,並且HTTP頭信息的X-HTTP-Method-Override屬性會設置爲實際的HTTP方法。
Vue.http.options.emulateHTTP = true;

emulateJSON的作用

如果Web服務器無法處理編碼爲application/json的請求,你可以啓用emulateJSON選項。啓用該選項後,請求會以application/x-www-form-urlencoded作爲MIME type,就像普通的HTML表單一樣。
Vue.http.options.emulateJSON = true;

response對象

response對象包含以下屬性:

方法類型描述
text()string以string形式返回response body
json()Object以JSON對象形式返回response body
blob()Blob以二進制形式返回response body
屬性類型描述
okboolean響應的HTTP狀態碼在200~299之間時,該屬性爲true
statusnumber響應的HTTP狀態碼
statusTextstring響應的狀態文本
headersObject響應頭

CURD實例

1、GET請求

var demo = new Vue({
  el: '#app',
  data: {
    gridColumns: ['customerId', 'companyName', 'contactName', 'phone'],
    gridData: [],
    apiUrl: 'http://211.149.193.19:8080/api/customers'
  },
  ready: function() {
    this.getCustomers()
  },
  methods: {
    getCustomers: function() {
      this.$http.get(this.apiUrl)
        .then((response) => {
          this.$set('gridData', response.data)
        })
        .catch(function(response) {
          console.log(response)
        })
    }
  }
})

這段程序的then方法只提供了successCallback,而省略了errorCallback。
catch方法用於捕捉程序的異常,catch方法和errorCallback是不同的,errorCallback只在響應失敗時調用,而catch則是在整個請求到響應過程中,只要程序出錯了就會被調用。
在then方法的回調函數內,你也可以直接使用this,this仍然是指向Vue實例的:

getCustomers: function() {
  this.$http.get(this.apiUrl)
    .then((response) => {
      this.$set('gridData', response.data)
    })
    .catch(function(response) {
      console.log(response)
    })
}

2、JSONP請求

getCustomers: function() {
  this.$http.jsonp(this.apiUrl).then(function(response){
    this.$set('gridData', response.data)
  })
}

3、POST請求

var demo = new Vue({
  el: '#app',
  data: {
    show: false,
    gridColumns: [{
      name: 'customerId',
      isKey: true
    }, {
      name: 'companyName'
    }, {
      name: 'contactName'
    }, {
      name: 'phone'
    }],
    gridData: [],
    apiUrl: 'http://211.149.193.19:8080/api/customers',
    item: {}
  },
  ready: function() {
    this.getCustomers()
  },
  methods: {
    closeDialog: function() {
      this.show = false
    },
    getCustomers: function() {
      var vm = this
      vm.$http.get(vm.apiUrl)
        .then((response) => {
          vm.$set('gridData', response.data)
        })
    },
    createCustomer: function() {
      var vm = this
      vm.$http.post(vm.apiUrl, vm.item)
        .then((response) => {
          vm.$set('item', {})
          vm.getCustomers()
        })
      this.show = false
    }
  }
})

4、PUT請求

updateCustomer: function() {
  var vm = this
  vm.$http.put(this.apiUrl + '/' + vm.item.customerId, vm.item)
    .then((response) => {
      vm.getCustomers()
    })
}

5、Delete請求

deleteCustomer: function(customer){
  var vm = this
  vm.$http.delete(this.apiUrl + '/' + customer.customerId)
    .then((response) => {
      vm.getCustomers()
    })
}

vue-resource是一個非常輕量的用於處理HTTP請求的插件,它提供了兩種方式來處理HTTP請求:
1、使用Vue.http或this.$http
2、使用Vue.resource或this.$resource

data(){
    return{
      toplist:[],
      alllist:[]
    }
  },
  //vue-router
  route:{
    data({to}){
      //併發請求,利用 Promise 
      return Promise.all([
        //簡寫
        this.$http.get('http://192.168.30.235:9999/rest/knowledge/list',{'websiteId':2,'pageSize':5,'pageNo':1,'isTop':1}),
        //this.$http.get('http://192.168.30.235:9999/rest/knowledge/list',{'websiteId':2,'pageSize':20,'pageNo':1,'isTop':0})
        //不簡寫
        this.$http({
          method:'GET',
          url:'http://192.168.30.235:9999/rest/knowledge/list',
          data:{'websiteId':2,'pageSize':20,'pageNo':1,'isTop':0},
          headers: {"X-Requested-With": "XMLHttpRequest"},
          emulateJSON: true
          })
        ]).then(function(data){//es5寫法
           return{
            toplist:data[0].data.knowledgeList,
            alllist:data[1].data.knowledgeList
          }
        //es6寫法 .then()部分
        //.then(([toplist,alllist])=>({toplist,alllist})) 
      },function(error){
        //error
      })
    }
  }

vue axios

vue2.0之後,就不再對vue-resource更新,而是推薦使用axios。基於 Promise 的 HTTP 請求客戶端,可同時在瀏覽器和 Node.js 中使用。

  • 功能特性
    1、在瀏覽器中發送 XMLHttpRequests 請求
    2、在 node.js 中發送 http請求
    3、支持 Promise API
    4、攔截請求和響應
    5、轉換請求和響應數據
    6、取消請求
    7、自動轉換 JSON 數據
    8、客戶端支持保護安全免受 CSRF/XSRF 攻擊
  • 安裝 axios
    $ npm install axios
  • 在要使用的文件中引入axios
    import axios from 'axios'
  • GET請求
// 向具有指定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);
});
  • POST請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
  • 執行多個併發請求
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) {
//兩個請求現已完成
}));
  • axios API:可以通過將相關配置傳遞給 axios 來進行請求。
axios(config)
// 發送一個 POST 請求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
axios(url[, config])
// 發送一個 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);
});
  • 配置默認值

1、全局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';

2、自定義實例默認值

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

3、配置優先級順序
配置將與優先順序合併。 順序是lib / defaults.js中的庫默認值,然後是實例的defaults屬性,最後是請求的config參數。 後者將優先於前者。 這裏有一個例子。

//使用庫提供的配置默認值創建實例
//此時,超時配置值爲`0`,這是庫的默認值
var instance = axios.create();
 
//覆蓋庫的超時默認值
//現在所有請求將在超時前等待2.5秒
instance.defaults.timeout = 2500;
 
//覆蓋此請求的超時,因爲它知道需要很長時間
instance.get('/ longRequest',{
   timeout:5000
});
  • 攔截器
    你可以截取請求或響應在被 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);
   });

如果你以後可能需要刪除攔截器。

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

你可以將攔截器添加到axios的自定義實例。

var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
  • 處理錯誤
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時拒絕
   }}
})
  • 消除
    您可以使用取消令牌取消請求。

    axios cancel token API基於可取消的promise提議,目前處於階段1
    您可以使用CancelToken.source工廠創建一個取消令牌,如下所示:

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 {
// 處理錯誤
}
});
 
//取消請求(消息參數是可選的)
source.cancel('操作被用戶取消。');

您還可以通過將執行器函數傳遞給CancelToken構造函數來創建取消令牌:

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

注意:您可以使用相同的取消令牌取消幾個請求。

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

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

1、瀏覽器
在瀏覽器中,您可以使用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 });

2、Node.js
在node.js中,可以使用querystring模塊,如下所示:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' });

3、TypeScript
axios包括TypeScript定義。

import axios from 'axios';
axios.get('/user?ID=12345');

axios在很大程度上受到Angular提供的$http服務的啓發。 最終,axios努力提供一個在Angular外使用的獨立的$http-like服務。

發佈了14 篇原創文章 · 獲贊 11 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章