vue-resource和vue axios (轉(zhuǎn))

vue-resource

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

vue-resource特點

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

體積小

vue-resource非常小巧,在壓縮以后只有大約12KB,服務(wù)端啟用gzip壓縮后只有4.5KB大小,這遠(yuǎn)比jQuery的體積要小得多。

支持主流的瀏覽器

和Vue.js一樣,vue-resource除了不支持IE 9以下的瀏覽器,其他主流的瀏覽器都支持。

支持Promise API和URI Templates

Promise是ES6的特性,Promise的中文含義為“先知”,Promise對象用于異步計算。

URI Templates表示URI模板,有些類似于ASP.NET MVC的路由模板。

支持?jǐn)r截器

攔截器是全局的,攔截器可以在請求發(fā)送前和發(fā)送請求后做一些處理。

攔截器在一些場景下會非常有用,比如請求發(fā)送前在headers中設(shè)置access_token,或者在請求失敗時,提供共通的處理方式。

vue-resource使用

1、引入vue-resource

<scriptsrc="js/vue.js"></script>

<scriptsrc="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實例內(nèi)使用$http

this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);

this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

在發(fā)送請求后,使用then方法來處理響應(yīng)結(jié)果,then方法有兩個參數(shù),第一個參數(shù)是響應(yīng)成功時的回調(diào)函數(shù),第二個參數(shù)是響應(yīng)失敗時的回調(diào)函數(shù)。

then方法的回調(diào)函數(shù)也有兩種寫法,第一種是傳統(tǒng)的函數(shù)寫法,第二種是更為簡潔的ES 6的Lambda寫法:

// 傳統(tǒng)寫法

this.$http.get('/someUrl', [options]).then(function(response){

// 響應(yīng)成功回調(diào)

},function(response){

// 響應(yīng)錯誤回調(diào)

});

// Lambda寫法

this.$http.get('/someUrl', [options]).then((response) => {

// 響應(yīng)成功回調(diào)

}, (response) => {

// 響應(yīng)錯誤回調(diào)

});

支持的HTTP方法

vue-resource的請求API是按照REST風(fēng)格設(shè)計的,它提供了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名稱是標(biāo)準(zhǔn)的HTTP方法。當(dāng)服務(wù)端使用REST API時,客戶端的編碼風(fēng)格和服務(wù)端的編碼風(fēng)格近乎一致,這可以減少前端和后端開發(fā)人員的溝通成本。

客戶端請求方法服務(wù)端處理方法

this.$http.get(...)Getxxx

this.$http.post(...)Postxxx

this.$http.put(...)Putxxx

this.$http.delete(...)Deletexxx

options對象

參數(shù)類型描述

urlstring請求的URL

methodstring請求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法

bodyObject, FormData stringrequest body

paramsObject請求的URL參數(shù)對象

headersObjectrequest header

timeoutnumber單位為毫秒的請求超時時間 (0 表示無超時時間)

beforefunction(request)請求發(fā)送前的處理函數(shù),類似于jQuery的beforeSend函數(shù)

progressfunction(event)ProgressEvent回調(diào)處理函數(shù)

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

emulateHTTPboolean發(fā)送PUT, PATCH, DELETE請求時以HTTP POST的方式發(fā)送,并設(shè)置請求頭的X-HTTP-Method-Override

emulateJSONboolean將request body以application/x-www-form-urlencoded content type發(fā)送

emulateHTTP的作用

如果Web服務(wù)器無法處理PUT, PATCH和DELETE這種REST風(fēng)格的請求,你可以啟用enulateHTTP現(xiàn)象。啟用該選項后,請求會以普通的POST方法發(fā)出,并且HTTP頭信息的X-HTTP-Method-Override屬性會設(shè)置為實際的HTTP方法。

Vue.http.options.emulateHTTP =true;

emulateJSON的作用

如果Web服務(wù)器無法處理編碼為application/json的請求,你可以啟用emulateJSON選項。啟用該選項后,請求會以application/x-www-form-urlencoded作為MIMEtype,就像普通的HTML表單一樣。

Vue.http.options.emulateJSON =true;

response對象

response對象包含以下屬性:

方法類型描述

text()string以string形式返回response body

json()Object以JSON對象形式返回response body

blob()Blob以二進(jìn)制形式返回response body

屬性類型描述

okboolean響應(yīng)的HTTP狀態(tài)碼在200~299之間時,該屬性為true

statusnumber響應(yīng)的HTTP狀態(tài)碼

statusTextstring響應(yīng)的狀態(tài)文本

headersObject響應(yīng)頭

CURD實例

1、GET請求

vardemo =newVue({

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只在響應(yīng)失敗時調(diào)用,而catch則是在整個請求到響應(yīng)過程中,只要程序出錯了就會被調(diào)用。

在then方法的回調(diào)函數(shù)內(nèi),你也可以直接使用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請求

vardemo =newVue({

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(){

varvm = this

? ? ? vm.$http.get(vm.apiUrl)

? ? ? ? .then((response) => {

vm.$set('gridData', response.data)

? ? ? ? })

? ? },

createCustomer:function(){

varvm = this

? ? ? vm.$http.post(vm.apiUrl, vm.item)

? ? ? ? .then((response) => {

vm.$set('item', {})

? ? ? ? ? vm.getCustomers()

? ? ? ? })

this.show =false

? ? }

? }

})

4、PUT請求

updateCustomer:function(){

varvm =this

vm.$http.put(this.apiUrl +'/'+ vm.item.customerId, vm.item)

.then((response) =>{

? ? ? vm.getCustomers()

? ? })

}

5、Delete請求

deleteCustomer:function(customer){

varvm =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}){

//并發(fā)請求,利用 Promise

returnPromise.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、在瀏覽器中發(fā)送 XMLHttpRequests 請求

2、在 node.js 中發(fā)送 http請求

3、支持 Promise API

4、攔截請求和響應(yīng)

5、轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)

6、取消請求

7、自動轉(zhuǎn)換 JSON 數(shù)據(jù)

8、客戶端支持保護(hù)安全免受 CSRF/XSRF 攻擊

安裝 axios

$ npm install axios

在要使用的文件中引入axios

import axios from 'axios'

GET請求

// 向具有指定ID的用戶發(fā)出請求

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

.then(function(response){

console.log(response);

})

.catch(function(error){

console.log(error);

});

// 也可以通過 params 對象傳遞參數(shù)

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

});

執(zhí)行多個并發(fā)請求

functiongetUserAccount(){

returnaxios.get('/user/12345');

}

functiongetUserPermissions(){

returnaxios.get('/user/12345/permissions');

}

axios.all([getUserAccount(), getUserPermissions()])

.then(axios.spread(function(acct, perms){

//兩個請求現(xiàn)已完成

}));

axios API:可以通過將相關(guān)配置傳遞給 axios 來進(jìn)行請求。

axios(config)

// 發(fā)送一個 POST 請求

axios({

method:'post',

url:'/user/12345',

data: {

firstName:'Fred',

lastName:'Flintstone'

}

});

axios(url[, config])

// 發(fā)送一個 GET 請求 (GET請求是默認(rèn)請求模式)

axios('/user/12345');

請求方法別名:

為了方便起見,已經(jīng)為所有支持的請求方法提供了別名。

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]])

注意:當(dāng)使用別名方法時,不需要在config中指定url,method和data屬性。

并發(fā)

幫助函數(shù)處理并發(fā)請求。

axios.all(iterable)

axios.spread(callback)

創(chuàng)建實例

也可以使用自定義配置創(chuàng)建axios的新實例。

axios.create([config])

varinstance = 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]])

請求配置

這些是用于發(fā)出請求的可用配置選項。 只有url是必需的。 如果未指定方法,請求將默認(rèn)為GET。

{

// `url`是將用于請求的服務(wù)器URL

url:'/user',

// `method`是發(fā)出請求時使用的請求方法

method:'get',// 默認(rèn)

// `baseURL`將被添加到`url`前面,除非`url`是絕對的。

// 可以方便地為 axios 的實例設(shè)置`baseURL`,以便將相對 URL 傳遞給該實例的方法。

baseURL:'https://some-domain.com/api/',

// `transformRequest`允許在請求數(shù)據(jù)發(fā)送到服務(wù)器之前對其進(jìn)行更改

// 這只適用于請求方法'PUT','POST'和'PATCH'

// 數(shù)組中的最后一個函數(shù)必須返回一個字符串,一個 ArrayBuffer或一個 Stream

transformRequest: [function(data){

// 做任何你想要的數(shù)據(jù)轉(zhuǎn)換

returndata;

}],

// `transformResponse`允許在 then / catch之前對響應(yīng)數(shù)據(jù)進(jìn)行更改

transformResponse: [function(data){

// Do whatever you want to transform the data

returndata;

}],

// `headers`是要發(fā)送的自定義 headers

headers: {'X-Requested-With':'XMLHttpRequest'},

// `params`是要與請求一起發(fā)送的URL參數(shù)

// 必須是純對象或URLSearchParams對象

params: {

ID:12345

},

// `paramsSerializer`是一個可選的函數(shù),負(fù)責(zé)序列化`params`

// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)

paramsSerializer:function(params){

returnQs.stringify(params, {arrayFormat:'brackets'})

},

// `data`是要作為請求主體發(fā)送的數(shù)據(jù)

// 僅適用于請求方法“PUT”,“POST”和“PATCH”

// 當(dāng)沒有設(shè)置`transformRequest`時,必須是以下類型之一:

// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams

// - Browser only: FormData, File, Blob

// - Node only: Stream

data: {

firstName:'Fred'

},

// `timeout`指定請求超時之前的毫秒數(shù)。

// 如果請求的時間超過'timeout',請求將被中止。

timeout:1000,

// `withCredentials`指示是否跨站點訪問控制請求

// should be made using credentials

withCredentials:false,// default

// `adapter'允許自定義處理請求,這使得測試更容易。

// 返回一個promise并提供一個有效的響應(yīng)(參見[response docs](#response-api))

adapter:function(config){

/* ... */

},

// `auth'表示應(yīng)該使用 HTTP 基本認(rèn)證,并提供憑據(jù)。

// 這將設(shè)置一個`Authorization'頭,覆蓋任何現(xiàn)有的`Authorization'自定義頭,使用`headers`設(shè)置。

auth: {

username:'janedoe',

password:'s00pers3cret'

},

// “responseType”表示服務(wù)器將響應(yīng)的數(shù)據(jù)類型

// 包括 '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`允許處理上傳的進(jìn)度事件

onUploadProgress:function(progressEvent){

// 使用本地 progress 事件做任何你想要做的

},

// `onDownloadProgress`允許處理下載的進(jìn)度事件

onDownloadProgress:function(progressEvent){

// Do whatever you want with the native progress event

},

// `maxContentLength`定義允許的http響應(yīng)內(nèi)容的最大大小

maxContentLength:2000,

// `validateStatus`定義是否解析或拒絕給定的promise

// HTTP響應(yīng)狀態(tài)碼。如果`validateStatus`返回`true`(或被設(shè)置為`null` promise將被解析;否則,promise將被

// 拒絕。

validateStatus:function(status){

returnstatus >=200&& status <300;// default

},

// `maxRedirects`定義在node.js中要遵循的重定向的最大數(shù)量。

// 如果設(shè)置為0,則不會遵循重定向。

maxRedirects:5,// 默認(rèn)

// `httpAgent`和`httpsAgent`用于定義在node.js中分別執(zhí)行http和https請求時使用的自定義代理。

// 允許配置類似`keepAlive`的選項,

// 默認(rèn)情況下不啟用。

httpAgent:newhttp.Agent({keepAlive:true}),

httpsAgent:newhttps.Agent({keepAlive:true}),

// 'proxy'定義代理服務(wù)器的主機名和端口

// `auth`表示HTTP Basic auth應(yīng)該用于連接到代理,并提供credentials。

// 這將設(shè)置一個`Proxy-Authorization` header,覆蓋任何使用`headers`設(shè)置的現(xiàn)有的`Proxy-Authorization` 自定義 headers。

proxy: {

host:'127.0.0.1',

port:9000,

auth: : {

username:'mikeymike',

password:'rapunz3l'

}

},

// “cancelToken”指定可用于取消請求的取消令牌

// (see Cancellation section below for details)

cancelToken:newCancelToken(function(cancel){

})

}

使用 then 時,將收到如下響應(yīng):

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

});

配置默認(rèn)值

1、全局axios默認(rèn)值

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、自定義實例默認(rèn)值

//在創(chuàng)建實例時設(shè)置配置默認(rèn)值

varinstance = axios.create({

baseURL:'https://api.example.com'

});

//在實例創(chuàng)建后改變默認(rèn)值

instance.defaults.headers.common ['Authorization'] =AUTH_TOKEN;

3、配置優(yōu)先級順序

配置將與優(yōu)先順序合并。 順序是lib / defaults.js中的庫默認(rèn)值,然后是實例的defaults屬性,最后是請求的config參數(shù)。 后者將優(yōu)先于前者。 這里有一個例子。

//使用庫提供的配置默認(rèn)值創(chuàng)建實例

//此時,超時配置值為`0`,這是庫的默認(rèn)值

varinstance = axios.create();

//覆蓋庫的超時默認(rèn)值

//現(xiàn)在所有請求將在超時前等待2.5秒

instance.defaults.timeout =2500;

//覆蓋此請求的超時,因為它知道需要很長時間

instance.get('/ longRequest',{

timeout:5000

});

攔截器

你可以截取請求或響應(yīng)在被 then 或者 catch 處理之前

//添加請求攔截器

axios.interceptors.request.use(function(config){

//在發(fā)送請求之前做某事

returnconfig;

},function(error){

//請求錯誤時做些事

returnPromise.reject(error);

? });

//添加響應(yīng)攔截器

axios.interceptors.response.use(function(response){

//對響應(yīng)數(shù)據(jù)做些事

returnresponse;

},function(error){

//請求錯誤時做些事

returnPromise.reject(error);

? });

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

varmyInterceptor = axios.interceptors.request.use(function(){/*...*/});

axios.interceptors.request.eject(myInterceptor);

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

varinstance = axios.create();

instance.interceptors.request.use(function(){/*...*/});

處理錯誤

axios.get('/ user / 12345')

.catch(function(error){

if(error.response){

//請求已發(fā)出,但服務(wù)器使用狀態(tài)代碼進(jìn)行響應(yīng)

//落在2xx的范圍之外

console.log(error.response.data);

console.log(error.response.status);

console.log(error.response.headers);

}else{

//在設(shè)置觸發(fā)錯誤的請求時發(fā)生了錯誤

console.log('Error',error.message);

? ? }}

console.log(error.config);

? });

您可以使用validateStatus配置選項定義自定義HTTP狀態(tài)碼錯誤范圍。

axios.get('/ user / 12345',{

validateStatus:function(status){

returnstatus <500;//僅當(dāng)狀態(tài)代碼大于或等于500時拒絕

? }}

})

消除

您可以使用取消令牌取消請求。

axios cancel token API基于可取消的promise提議,目前處于階段1

您可以使用CancelToken.source工廠創(chuàng)建一個取消令牌,如下所示:

varCancelToken = axios.CancelToken;

varsource = CancelToken.source();

axios.get('/user/12345', {

cancelToken: source.token

}).catch(function(thrown){

if(axios.isCancel(thrown)) {

console.log('Request canceled', thrown.message);

}else{

// 處理錯誤

}

});

//取消請求(消息參數(shù)是可選的)

source.cancel('操作被用戶取消。');

您還可以通過將執(zhí)行器函數(shù)傳遞給CancelToken構(gòu)造函數(shù)來創(chuàng)建取消令牌:

varCancelToken = axios.CancelToken;

varcancel;

axios.get('/ user / 12345',{

cancelToken:newCancelToken(functionexecutor(c){

//一個執(zhí)行器函數(shù)接收一個取消函數(shù)作為參數(shù)

? ? cancel = c;

? })

});

// 取消請求

clear();

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

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

默認(rèn)情況下,axios將JavaScript對象序列化為JSON。 要以應(yīng)用程序/ x-www-form-urlencoded格式發(fā)送數(shù)據(jù),您可以使用以下選項之一。

1、瀏覽器

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

varparams=newURLSearchParams();

params.append('param1','value1');

params.append('param2','value2');

axios.post('/foo',params);

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

或者,您可以使用qs庫對數(shù)據(jù)進(jìn)行編碼:

varqs =require('qs');

axios.post('/foo', qs.stringify({'bar':123});

2、Node.js

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

varquerystring =require('querystring');

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

3、TypeScript

axios包括TypeScript定義。

importaxiosfrom'axios';

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

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容