@1 第一步 我們一般都會先導入axios
? ? ? ? import axios from ‘a(chǎn)xios’
@2?第二步 創(chuàng)建axios的實例 可以同時創(chuàng)建多個實例 每個實例配置不同
? ? ? ? const http?= axios.create( {?
? ? ? ? ????????// 這里面可以做一些基礎的配置 比如基礎路徑 ,axios 請求超時的時間
? ? ? ? ????????baseURL:'https://www.baidu.com',
? ? ? ? ? ? ? ? timeout:60000
?????????})
@3 只針對post請求,請求主體做格式化的處理,安裝后臺的要求,如果不設置transfromRequest
? ? ? ? 會把Data對象轉化為JSON字符串傳遞給服務器, axios內部會識別常用的數(shù)據(jù)格式,自動設
????????置請求頭中的Content-Type
? ? ? ? http.defaults.transfromRequest = data =>{
? ? ? ? ? ? ? ? if(typeof data === 'object') qs.stringfy(data)? ?// qs.stringfy是轉化為name='zs'$age=12
? ? ? ? ? ? ? ? return data
????????}
? ? ? ? http.default.validateStatus = status = > {
? ? ? ? ? ? ? ? return status >= 200 && status < 400? // 設置狀態(tài)碼在200到400之間都是成功的
????????}
@4 設置請求攔截器? 并且攜帶token
? ? ? ? http.interceptors.request.use(config=>{
? ? ? ? ? ? ? ? if(localstorags.getItem('token')){
? ? ? ? ? ? ? ? ? ? ? ? config.headers.authorzation = localstorage.getItem('token')
?????????????????}
? ? ? ? ? ? ? ? return config
????????})
@5 設置響應攔截器
? ? ? ? http.intercepotrs.response.use(responst=>{
? ? ? ? ? ? ? ? return responst.data
????????}, reson=>{文章來源:http://www.zghlxwxcb.cn/news/detail-778262.html
? ? ? ? ? ? ? ? ?// 請求失敗的處理
? ? ? ? ? ? ? ? let status = reson?.reponse.status
? ? ? ? ? ? ? ? ? ? ?code = reson?.code
? ? ? ? ? ? ? ? if(status){?
? ? ? ? ? ? ? ? ? ? ? ? // 服務器返回的有結果 沒有經(jīng)過validateStatus狀態(tài)碼的校驗
? ? ? ? ? ? ? ? ? ? ? ? switch(+status){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? case 404:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? alert('請求地址不存在')
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ????????break;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? case 500:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? alert('服務器發(fā)生未知錯誤')
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ????????break;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 。。。
????????????????????????}
???????????????? }else if(code==='ECONNABORTED'){
? ? ? ? ? ? ? ? ? ? ? ? // 請求超時
? ? ? ? ? ? ? ? ? ? ? ? alert(‘當前請求超時’)
????????????????}else if(axios.isCancel(reson)){
? ? ? ? ? ? ? ? ? ? ? ? // 請求中斷
? ? ? ? ? ? ? ? ? ? ? ? alert('請求中斷')
????????????????}else {
? ? ? ? ? ? ? ? ? ? ? ? alert(‘網(wǎng)絡中斷,請檢查網(wǎng)絡')
????????????????}
? ? ? ? ? ? ? ? return Promise.reject(reson)
????????})
@ 6 記得導出
? ? ? ? export default http文章來源地址http://www.zghlxwxcb.cn/news/detail-778262.html
到了這里,關于關于axios的二次封裝的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!