鍍金池/ 問答/HTML/ vue 使用axios怎么更改請求攔截器?

vue 使用axios怎么更改請求攔截器?

// 引入axios以及element ui中的loading和message組件
import axios from 'axios'
import { Loading, Message } from 'element-ui'
// 超時時間
axios.defaults.timeout = 5000
// http請求攔截器
var loadinginstace
axios.interceptors.request.use(config => {
// element ui Loading方法
loadinginstace = Loading.service({ fullscreen: true })
return config
}, error => {
loadinginstace.close()
Message.error({

message: '加載超時'

})
return Promise.reject(error)
})
// http響應(yīng)攔截器
axios.interceptors.response.use(data => {// 響應(yīng)成功關(guān)閉loading
loadinginstace.close()
return data
}, error => {
loadinginstace.close()
Message.error({

message: '加載失敗'

})
return Promise.reject(error)
})

export default axios

比如這個有時候 不想跳出elementUI 的 loading 要怎么修改設(shè)置呢?
求大神指點?。。?!

回答
編輯回答
吢丕

可以加一個開關(guān),放在全局還是vue哪里,隨便你,通過控制這個開關(guān)來控制是否顯示loading

loadinginstace = showLoading && Loading.service({ fullscreen: true })

loadinginstace && loadinginstace.close()
2017年1月29日 11:58
編輯回答
爛人

這是個axios的攔截器,判斷只有狀態(tài)嗎返回200~300才會接收數(shù)據(jù),而且請求超時時間為10秒,失敗后自動發(fā)起下一次請求,一共請求4次

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
//axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'
axios.defaults.retry = 4
axios.defaults.timeout = 10000
axios.defaults.withCredentials = true
// code狀態(tài)碼200判斷
axios.interceptors.response.use((res) => {
    if(res.status === 654) {
        console.log('請求超時!')
    }
    if(res.data.code < 200 && res.data.code >= 300) {
        console.error('數(shù)據(jù)返回有誤')
        return Promise.reject(res)
    }
    return res
}, (error) => {
    let config = error.config
    if(!config || !config.retry) return Promise.reject(error)
    config.__retryCount = config.__retryCount || 0
    
    if(config.__retryCount >= config.retry) {
        console.log('promise error:' + error)
        return Promise.reject(error)
    }
    config.__retryCount += 1
    let backoff = new Promise(function(resolve) {
        setTimeout(function() {
            resolve()
        }, config.retryDelay || 1)
    })
    
    return backoff.then(function() {
        return axios(config)
    })
})
2018年3月1日 05:17