Vue官方推薦AJAX組件axios.js使用方法詳解與API
Axios.js作為Vue官方插件的AJAX組件其主要有以下幾個特點:
1、比Jquery輕量,但處理請求不多的時候,可以使用
2、基于Promise語法標準
3、支持nodejs
4、自動轉換JSON數(shù)據(jù)
Axios.js用法
axios提供了一下幾種請求方式
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ā)送一個GET請求
//通過給定的ID來發(fā)送請求
axios.get('/user?ID=12345')
.then(function(response){
console.log(response);
})
.catch(function(err){
console.log(err);
});
//以上請求也可以通過這種方式來發(fā)送
axios.get('/user',{
params:{
ID:12345
}
})
.then(function(response){
console.log(response);
})
.catch(function(err){
console.log(err);
});
2、 發(fā)送一個POST請求
axios.post('/user',{
firstName:'Fred',
lastName:'Flintstone'
})
.then(function(res){
console.log(res);
})
.catch(function(err){
console.log(err);
});
3、 一次性并發(fā)多個請求
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){
//當這兩個請求都完成的時候會觸發(fā)這個函數(shù),兩個參數(shù)分別代表返回的結果
}))
axios的API
(一) axios可以通過配置(config)來發(fā)送請求
1、 axios(config)
//發(fā)送一個`POST`請求
axios({
method:"POST",
url:'/user/12345',
data:{
firstName:"Fred",
lastName:"Flintstone"
}
});
2、 axios(url[,config])
//發(fā)送一個`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]])
注意:當我們在使用別名方法的時候,url,method,data這幾個參數(shù)不需要在配置中聲明
(三)、 并發(fā)請求(concurrency),即是幫助處理并發(fā)請求的輔助函數(shù)
//iterable是一個可以迭代的參數(shù)如數(shù)組 axios.all(iterable) //callback要等到所有請求都完成才會執(zhí)行 axios.spread(callback)
(四)、創(chuàng)建一個axios實例,并且可以自定義其配置
1、 axios.create([config])
var instance = axios.create({
baseURL:"https://some-domain.com/api/",
timeout:1000,
headers: {'X-Custom-Header':'foobar'}
});
2、 實例的方法
一下是實例方法,注意已經定義的配置將和利用create創(chuà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]])
Axios請求的配置(request config)
以下就是請求的配置選項,只有url選項是必須的,如果method選項未定義,那么它默認是以GET的方式發(fā)出請求
{
//`url`是請求的服務器地址
url:'/user',
//`method`是請求資源的方式
method:'get'//default
//如果`url`不是絕對地址,那么`baseURL`將會加到`url`的前面
//當`url`是相對地址的時候,設置`baseURL`會非常的方便
baseURL:'https://some-domain.com/api/',
//`transformRequest`選項允許我們在請求發(fā)送到服務器之前對請求的數(shù)據(jù)做出一些改動
//該選項只適用于以下請求方式:`put/post/patch`
//數(shù)組里面的最后一個函數(shù)必須返回一個字符串、-一個`ArrayBuffer`或者`Stream`
transformRequest:[function(data){
//在這里根據(jù)自己的需求改變數(shù)據(jù)
return data;
}],
//`transformResponse`選項允許我們在數(shù)據(jù)傳送到`then/catch`方法之前對數(shù)據(jù)進行改動
transformResponse:[function(data){
//在這里根據(jù)自己的需求改變數(shù)據(jù)
return data;
}],
//`headers`選項是需要被發(fā)送的自定義請求頭信息
headers: {'X-Requested-With':'XMLHttpRequest'},
//`params`選項是要隨請求一起發(fā)送的請求參數(shù)----一般鏈接在URL后面
//他的類型必須是一個純對象或者是URLSearchParams對象
params: {
ID:12345
},
//`paramsSerializer`是一個可選的函數(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`選項是作為一個請求體而需要被發(fā)送的數(shù)據(jù)
//該選項只適用于方法:`put/post/patch`
//當沒有設置`transformRequest`選項時dada必須是以下幾種類型之一
//string/plain/object/ArrayBuffer/ArrayBufferView/URLSearchParams
//僅僅瀏覽器:FormData/File/Bold
//僅node:Stream
data {
firstName:"Fred"
},
//`timeout`選項定義了請求發(fā)出的延遲毫秒數(shù)
//如果請求花費的時間超過延遲的時間,那么請求會被終止
timeout:1000,
//`withCredentails`選項表明了是否是跨域請求
withCredentials:false,//default
//`adapter`適配器選項允許自定義處理請求,這會使得測試變得方便
//返回一個promise,并提供驗證返回
adapter: function(config){
/*..........*/
},
//`auth`表明HTTP基礎的認證應該被使用,并提供證書
//這會設置一個authorization頭(header),并覆蓋你在header設置的Authorization頭信息
auth: {
username:"zhangsan",
password: "s00sdkf"
},
//返回數(shù)據(jù)的格式
//其可選項是arraybuffer,blob,document,json,text,stream
responseType:'json',//default
//
xsrfCookieName: 'XSRF-TOKEN',//default
xsrfHeaderName:'X-XSRF-TOKEN',//default
//`onUploadProgress`上傳進度事件
onUploadProgress:function(progressEvent){
//下載進度的事件
onDownloadProgress:function(progressEvent){
}
},
//相應內容的最大值
maxContentLength:2000,
//`validateStatus`定義了是否根據(jù)http相應狀態(tài)碼,來resolve或者reject promise
//如果`validateStatus`返回true(或者設置為`null`或者`undefined`),那么promise的狀態(tài)將會是resolved,否則其狀態(tài)就是rejected
validateStatus:function(status){
return status >= 200 && status <300;//default
},
//`maxRedirects`定義了在nodejs中重定向的最大數(shù)量
maxRedirects: 5,//default
//`httpAgent/httpsAgent`定義了當發(fā)送http/https請求要用到的自定義代理
//keeyAlive在選項中沒有被默認激活
httpAgent: new http.Agent({keeyAlive:true}),
httpsAgent: new https.Agent({keeyAlive:true}),
//proxy定義了主機名字和端口號,
//`auth`表明http基本認證應該與proxy代理鏈接,并提供證書
//這將會設置一個`Proxy-Authorization` header,并且會覆蓋掉已經存在的`Proxy-Authorization` header
proxy: {
host:'127.0.0.1',
port: 9000,
auth: {
username:'skda',
password:'radsd'
}
},
//`cancelToken`定義了一個用于取消請求的cancel token
//詳見cancelation部分
cancelToken: new cancelToken(function(cancel){
})
}
Axios請求返回的內容
{
data:{},
status:200,
//從服務器返回的http狀態(tài)文本
statusText:'OK',
//響應頭信息
headers: {},
//`config`是在請求的時候的一些配置信息
config: {}
}
你可以這樣來獲取響應信息
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默認配置
你可以設置默認配置,對所有請求都有效
1、 全局默認配置
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、 自定義的實例默認設置
//當創(chuàng)建實例的時候配置默認配置
var instance = axios.create({
baseURL: 'https://api.example.com'
});
//當實例創(chuàng)建時候修改配置
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;
3、 配置中的有優(yōu)先級
config配置將會以優(yōu)先級別來合并,順序是lib/defauts.js中的默認配置,然后是實例中的默認配置,最后是請求中的config參數(shù)的配置,越往后等級越高,后面的會覆蓋前面的例子。
//創(chuàng)建一個實例的時候會使用libray目錄中的默認配置
//在這里timeout配置的值為0,來自于libray的默認值
var instance = axios.create();
//回覆蓋掉library的默認值
//現(xiàn)在所有的請求都要等2.5S之后才會發(fā)出
instance.defaults.timeout = 2500;
//這里的timeout回覆蓋之前的2.5S變成5s
instance.get('/longRequest',{
timeout: 5000
});
Axios攔截器
你可以在請求、響應在到達then/catch之前攔截他們
//添加一個請求攔截器
axios.interceptors.request.use(function(config){
//在請求發(fā)出之前進行一些操作
return config;
},function(err){
//Do something with request error
return Promise.reject(error);
});
//添加一個響應攔截器
axios.interceptors.response.use(function(res){
//在這里對返回的數(shù)據(jù)進行處理
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實例添加攔截器
var instance = axios.create();
instance.interceptors.request.use(function(){})
Axios錯誤處理
axios.get('/user/12345')
.catch(function(error){
if(error.response){
//請求已經發(fā)出,但是服務器響應返回的狀態(tài)嗎不在2xx的范圍內
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.header);
}else {
//一些錯誤是在設置請求的時候觸發(fā)
console.log('Error',error.message);
}
console.log(error.config);
});
Axios取消請求
你可以通過一個cancel token來取消一個請求
你可以通過CancelToken.source工廠函數(shù)來創(chuàng)建一個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
}
});
//取消請求(信息的參數(shù)可以設置的)
source.cance("操作被用戶取消");
你可以給cancelToken構造函數(shù)傳遞一個executor function來創(chuàng)建一個cancel token:
var cancelToken = axios.CancelToken;
var cance;
axios.get('/user/12345',{
cancelToken: new CancelToken(function(c){
//這個executor函數(shù)接受一個cancel function作為參數(shù)
cancel = c;
})
})
//取消請求
cancel();
以上即是Axios.js的詳細使用方法與API,想了解更多關于Axios.js庫的相關知識點擊下面的相關文章
相關文章
vue 解決無法對未定義的值,空值或基元值設置反應屬性報錯問題
這篇文章主要介紹了vue 解決無法對未定義的值,空值或基元值設置反應屬性報錯問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
vue3動態(tài)加載組件以及動態(tài)引入組件詳解
?平常的vue項目開發(fā),已經很難遇見一千行,甚至幾千行代碼的頁面了,畢竟大家都會去拆分組件,下面這篇文章主要給大家介紹了關于vue3動態(tài)加載組件以及動態(tài)引入組件的相關資料,需要的朋友可以參考下2023-03-03
React/vue開發(fā)報錯TypeError:this.getOptions?is?not?a?function
這篇文章主要給大家介紹了關于React/vue開發(fā)報錯TypeError:this.getOptions?is?not?a?function的解決方法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-07-07
vue的el-select綁定的值無法選中el-option問題及解決
這篇文章主要介紹了vue的el-select綁定的值無法選中el-option問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
vue生命周期beforeDestroy和destroyed調用方式
這篇文章主要介紹了vue生命周期beforeDestroy和destroyed調用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
Vue使用pinia管理數(shù)據(jù)pinia持久化存儲問題
這篇文章主要介紹了Vue使用pinia管理數(shù)據(jù)pinia持久化存儲問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
Vue3 elementUI如何修改el-date-picker默認時間
這篇文章主要介紹了Vue3 elementUI如何修改el-date-picker默認時間,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08

