Vue官方推薦AJAX組件axios.js使用方法詳解與API
Axios.js作為Vue官方插件的AJAX組件其主要有以下幾個(gè)特點(diǎn):
1、比Jquery輕量,但處理請(qǐng)求不多的時(shí)候,可以使用
2、基于Promise語法標(biāo)準(zhǔn)
3、支持nodejs
4、自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)
Axios.js用法
axios提供了一下幾種請(qǐ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]])
1、發(fā)送一個(gè)GET請(qǐng)求
//通過給定的ID來發(fā)送請(qǐng)求
axios.get('/user?ID=12345')
.then(function(response){
console.log(response);
})
.catch(function(err){
console.log(err);
});
//以上請(qǐng)求也可以通過這種方式來發(fā)送
axios.get('/user',{
params:{
ID:12345
}
})
.then(function(response){
console.log(response);
})
.catch(function(err){
console.log(err);
});
2、 發(fā)送一個(gè)POST請(qǐng)求
axios.post('/user',{
firstName:'Fred',
lastName:'Flintstone'
})
.then(function(res){
console.log(res);
})
.catch(function(err){
console.log(err);
});
3、 一次性并發(fā)多個(gè)請(qǐng)求
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){
//當(dāng)這兩個(gè)請(qǐng)求都完成的時(shí)候會(huì)觸發(fā)這個(gè)函數(shù),兩個(gè)參數(shù)分別代表返回的結(jié)果
}))
axios的API
(一) axios可以通過配置(config)來發(fā)送請(qǐng)求
1、 axios(config)
//發(fā)送一個(gè)`POST`請(qǐng)求
axios({
method:"POST",
url:'/user/12345',
data:{
firstName:"Fred",
lastName:"Flintstone"
}
});
2、 axios(url[,config])
//發(fā)送一個(gè)`GET`請(qǐng)求(默認(rèn)的請(qǐng)求方式)
axios('/user/12345');
(二)、 請(qǐng)求方式的別名,這里對(duì)所有已經(jīng)支持的請(qǐ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)我們?cè)谑褂脛e名方法的時(shí)候,url,method,data這幾個(gè)參數(shù)不需要在配置中聲明
(三)、 并發(fā)請(qǐng)求(concurrency),即是幫助處理并發(fā)請(qǐng)求的輔助函數(shù)
//iterable是一個(gè)可以迭代的參數(shù)如數(shù)組 axios.all(iterable) //callback要等到所有請(qǐng)求都完成才會(huì)執(zhí)行 axios.spread(callback)
(四)、創(chuàng)建一個(gè)axios實(shí)例,并且可以自定義其配置
1、 axios.create([config])
var instance = axios.create({
baseURL:"https://some-domain.com/api/",
timeout:1000,
headers: {'X-Custom-Header':'foobar'}
});
2、 實(shí)例的方法
一下是實(shí)例方法,注意已經(jīng)定義的配置將和利用create創(chuàng)建的實(shí)例的配置合并
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]])
Axios請(qǐng)求的配置(request config)
以下就是請(qǐng)求的配置選項(xiàng),只有url選項(xiàng)是必須的,如果method選項(xiàng)未定義,那么它默認(rèn)是以GET的方式發(fā)出請(qǐng)求
{
//`url`是請(qǐng)求的服務(wù)器地址
url:'/user',
//`method`是請(qǐng)求資源的方式
method:'get'//default
//如果`url`不是絕對(duì)地址,那么`baseURL`將會(huì)加到`url`的前面
//當(dāng)`url`是相對(duì)地址的時(shí)候,設(shè)置`baseURL`會(huì)非常的方便
baseURL:'https://some-domain.com/api/',
//`transformRequest`選項(xiàng)允許我們?cè)谡?qǐng)求發(fā)送到服務(wù)器之前對(duì)請(qǐng)求的數(shù)據(jù)做出一些改動(dòng)
//該選項(xiàng)只適用于以下請(qǐng)求方式:`put/post/patch`
//數(shù)組里面的最后一個(gè)函數(shù)必須返回一個(gè)字符串、-一個(gè)`ArrayBuffer`或者`Stream`
transformRequest:[function(data){
//在這里根據(jù)自己的需求改變數(shù)據(jù)
return data;
}],
//`transformResponse`選項(xiàng)允許我們?cè)跀?shù)據(jù)傳送到`then/catch`方法之前對(duì)數(shù)據(jù)進(jìn)行改動(dòng)
transformResponse:[function(data){
//在這里根據(jù)自己的需求改變數(shù)據(jù)
return data;
}],
//`headers`選項(xiàng)是需要被發(fā)送的自定義請(qǐng)求頭信息
headers: {'X-Requested-With':'XMLHttpRequest'},
//`params`選項(xiàng)是要隨請(qǐng)求一起發(fā)送的請(qǐng)求參數(shù)----一般鏈接在URL后面
//他的類型必須是一個(gè)純對(duì)象或者是URLSearchParams對(duì)象
params: {
ID:12345
},
//`paramsSerializer`是一個(gè)可選的函數(shù),起作用是讓參數(shù)(params)序列化
//例如(https://www.npmjs.com/package/qs,http://api.jquery.com/jquery.param)
paramsSerializer: function(params){
return Qs.stringify(params,{arrayFormat:'brackets'})
},
//`data`選項(xiàng)是作為一個(gè)請(qǐng)求體而需要被發(fā)送的數(shù)據(jù)
//該選項(xiàng)只適用于方法:`put/post/patch`
//當(dāng)沒有設(shè)置`transformRequest`選項(xiàng)時(shí)dada必須是以下幾種類型之一
//string/plain/object/ArrayBuffer/ArrayBufferView/URLSearchParams
//僅僅瀏覽器:FormData/File/Bold
//僅node:Stream
data {
firstName:"Fred"
},
//`timeout`選項(xiàng)定義了請(qǐng)求發(fā)出的延遲毫秒數(shù)
//如果請(qǐng)求花費(fèi)的時(shí)間超過延遲的時(shí)間,那么請(qǐng)求會(huì)被終止
timeout:1000,
//`withCredentails`選項(xiàng)表明了是否是跨域請(qǐng)求
withCredentials:false,//default
//`adapter`適配器選項(xiàng)允許自定義處理請(qǐng)求,這會(huì)使得測(cè)試變得方便
//返回一個(gè)promise,并提供驗(yàn)證返回
adapter: function(config){
/*..........*/
},
//`auth`表明HTTP基礎(chǔ)的認(rèn)證應(yīng)該被使用,并提供證書
//這會(huì)設(shè)置一個(gè)authorization頭(header),并覆蓋你在header設(shè)置的Authorization頭信息
auth: {
username:"zhangsan",
password: "s00sdkf"
},
//返回?cái)?shù)據(jù)的格式
//其可選項(xiàng)是arraybuffer,blob,document,json,text,stream
responseType:'json',//default
//
xsrfCookieName: 'XSRF-TOKEN',//default
xsrfHeaderName:'X-XSRF-TOKEN',//default
//`onUploadProgress`上傳進(jìn)度事件
onUploadProgress:function(progressEvent){
//下載進(jìn)度的事件
onDownloadProgress:function(progressEvent){
}
},
//相應(yīng)內(nèi)容的最大值
maxContentLength:2000,
//`validateStatus`定義了是否根據(jù)http相應(yīng)狀態(tài)碼,來resolve或者reject promise
//如果`validateStatus`返回true(或者設(shè)置為`null`或者`undefined`),那么promise的狀態(tài)將會(huì)是resolved,否則其狀態(tài)就是rejected
validateStatus:function(status){
return status >= 200 && status <300;//default
},
//`maxRedirects`定義了在nodejs中重定向的最大數(shù)量
maxRedirects: 5,//default
//`httpAgent/httpsAgent`定義了當(dāng)發(fā)送http/https請(qǐng)求要用到的自定義代理
//keeyAlive在選項(xiàng)中沒有被默認(rèn)激活
httpAgent: new http.Agent({keeyAlive:true}),
httpsAgent: new https.Agent({keeyAlive:true}),
//proxy定義了主機(jī)名字和端口號(hào),
//`auth`表明http基本認(rèn)證應(yīng)該與proxy代理鏈接,并提供證書
//這將會(huì)設(shè)置一個(gè)`Proxy-Authorization` header,并且會(huì)覆蓋掉已經(jīng)存在的`Proxy-Authorization` header
proxy: {
host:'127.0.0.1',
port: 9000,
auth: {
username:'skda',
password:'radsd'
}
},
//`cancelToken`定義了一個(gè)用于取消請(qǐng)求的cancel token
//詳見cancelation部分
cancelToken: new cancelToken(function(cancel){
})
}
Axios請(qǐng)求返回的內(nèi)容
{
data:{},
status:200,
//從服務(wù)器返回的http狀態(tài)文本
statusText:'OK',
//響應(yīng)頭信息
headers: {},
//`config`是在請(qǐng)求的時(shí)候的一些配置信息
config: {}
}
你可以這樣來獲取響應(yīng)信息
axios.get('/user/12345')
.then(function(res){
console.log(res.data);
console.log(res.status);
console.log(res.statusText);
console.log(res.headers);
console.log(res.config);
})
Axios默認(rèn)配置
你可以設(shè)置默認(rèn)配置,對(duì)所有請(qǐng)求都有效
1、 全局默認(rèn)配置
axios.defaults.baseURL = 'http://api.exmple.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';
2、 自定義的實(shí)例默認(rèn)設(shè)置
//當(dāng)創(chuàng)建實(shí)例的時(shí)候配置默認(rèn)配置
var instance = axios.create({
baseURL: 'https://api.example.com'
});
//當(dāng)實(shí)例創(chuàng)建時(shí)候修改配置
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;
3、 配置中的有優(yōu)先級(jí)
config配置將會(huì)以優(yōu)先級(jí)別來合并,順序是lib/defauts.js中的默認(rèn)配置,然后是實(shí)例中的默認(rèn)配置,最后是請(qǐng)求中的config參數(shù)的配置,越往后等級(jí)越高,后面的會(huì)覆蓋前面的例子。
//創(chuàng)建一個(gè)實(shí)例的時(shí)候會(huì)使用libray目錄中的默認(rèn)配置
//在這里timeout配置的值為0,來自于libray的默認(rèn)值
var instance = axios.create();
//回覆蓋掉library的默認(rèn)值
//現(xiàn)在所有的請(qǐng)求都要等2.5S之后才會(huì)發(fā)出
instance.defaults.timeout = 2500;
//這里的timeout回覆蓋之前的2.5S變成5s
instance.get('/longRequest',{
timeout: 5000
});
Axios攔截器
你可以在請(qǐng)求、響應(yīng)在到達(dá)then/catch之前攔截他們
//添加一個(gè)請(qǐng)求攔截器
axios.interceptors.request.use(function(config){
//在請(qǐng)求發(fā)出之前進(jìn)行一些操作
return config;
},function(err){
//Do something with request error
return Promise.reject(error);
});
//添加一個(gè)響應(yīng)攔截器
axios.interceptors.response.use(function(res){
//在這里對(duì)返回的數(shù)據(jù)進(jìn)行處理
return res;
},function(err){
//Do something with response error
return Promise.reject(error);
})
Axios取消攔截器
var myInterceptor = axios.interceptor.request.use(function(){/*....*/});
axios.interceptors.request.eject(myInterceptor);
3、 給自定義的axios實(shí)例添加攔截器
var instance = axios.create();
instance.interceptors.request.use(function(){})
Axios錯(cuò)誤處理
axios.get('/user/12345')
.catch(function(error){
if(error.response){
//請(qǐng)求已經(jīng)發(fā)出,但是服務(wù)器響應(yīng)返回的狀態(tài)嗎不在2xx的范圍內(nèi)
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.header);
}else {
//一些錯(cuò)誤是在設(shè)置請(qǐng)求的時(shí)候觸發(fā)
console.log('Error',error.message);
}
console.log(error.config);
});
Axios取消請(qǐng)求
你可以通過一個(gè)cancel token來取消一個(gè)請(qǐng)求
你可以通過CancelToken.source工廠函數(shù)來創(chuàng)建一個(gè)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 {
//handle error
}
});
//取消請(qǐng)求(信息的參數(shù)可以設(shè)置的)
source.cance("操作被用戶取消");
你可以給cancelToken構(gòu)造函數(shù)傳遞一個(gè)executor function來創(chuàng)建一個(gè)cancel token:
var cancelToken = axios.CancelToken;
var cance;
axios.get('/user/12345',{
cancelToken: new CancelToken(function(c){
//這個(gè)executor函數(shù)接受一個(gè)cancel function作為參數(shù)
cancel = c;
})
})
//取消請(qǐng)求
cancel();
以上即是Axios.js的詳細(xì)使用方法與API,想了解更多關(guān)于Axios.js庫的相關(guān)知識(shí)點(diǎn)擊下面的相關(guān)文章
相關(guān)文章
vue.js 輸入框輸入值自動(dòng)過濾特殊字符替換中問標(biāo)點(diǎn)操作
這篇文章主要介紹了vue.js 輸入框輸入值自動(dòng)過濾特殊字符替換中問標(biāo)點(diǎn)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-08-08
vue.nextTick()與setTimeout的區(qū)別及說明
這篇文章主要介紹了vue.nextTick()與setTimeout的區(qū)別及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
Vue中的watch是什么以及watch和computed的區(qū)別
這篇文章主要介紹了Vue中的watch是什么以及watch和computed的區(qū)別說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
如何在Vue項(xiàng)目中添加接口監(jiān)聽遮罩
這篇文章主要介紹了如何在Vue項(xiàng)目中添加接口監(jiān)聽遮罩,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
vue項(xiàng)目優(yōu)化之通過keep-alive數(shù)據(jù)緩存的方法
本篇文章主要介紹了vue項(xiàng)目優(yōu)化之通過keep-alive數(shù)據(jù)緩存的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12
vue如何實(shí)現(xiàn)拖動(dòng)圖片進(jìn)行排序Vue.Draggable
這篇文章主要介紹了vue如何實(shí)現(xiàn)拖動(dòng)圖片進(jìn)行排序Vue.Draggable,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
vue3監(jiān)聽resize窗口事件(離開頁面要銷毀窗口事件)
這篇文章主要給大家介紹了關(guān)于vue3監(jiān)聽resize窗口事件(離開頁面要銷毀窗口事件)的相關(guān)資料,vue是單頁面應(yīng)用,路由切換后,定時(shí)器并不會(huì)自動(dòng)關(guān)閉,需要手動(dòng)清除,當(dāng)頁面被銷毀時(shí),清除定時(shí)器即可,需要的朋友可以參考下2023-11-11

