axios取消請求與避免重復(fù)請求
起源
某個頁面需要下載全部數(shù)據(jù)的功能,下載數(shù)據(jù)量大,接口延遲長.....
某個頁面加載初始數(shù)據(jù)量延長長,但單個檢索快速,出現(xiàn)初始數(shù)據(jù)加載中時,檢索接口返回,初始數(shù)據(jù)后續(xù)返回覆蓋了檢索數(shù)據(jù)的展示....
這些情況需要我們:
- 能夠手動取消/終止請求Request。
- 某些頁面接口同時只能有一個在請求。
現(xiàn)狀
系統(tǒng)基于老哥花褲衩開源的vue-element-admin做的二次開發(fā),其中的請求采用的是axios,其中封裝的request.js關(guān)鍵代碼如下所示:
// create an axios instance const service = axios.create({ baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url withCredentials: true, // send cookies when cross-domain requests timeout: 500000, // request timeout transformRequest: [function(data) { // 對 data 進(jìn)行任意轉(zhuǎn)換處理 return Qs.stringify({ ...data }, // 數(shù)組的轉(zhuǎn)換 { arrayFormat: 'brackets' }) }] }) // request interceptor service.interceptors.request.use( config => { // do something before request is sent if (store.getters.token) { // let each request carry token // ['X-Token'] is a custom headers key // please modify it according to the actual situation config.headers['token'] = getToken() } return config }, error => { // do something with request error console.log(error) // for debug return Promise.reject(error) } )
發(fā)起請求的方法:
export function remoteApi(data) { return request({ url: '/api', method: 'post', data }) }
取消請求 cancelToken
其官方文檔:取消:
const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // 處理錯誤 } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // 取消請求(message 參數(shù)是可選的) source.cancel('Operation canceled by the user.');
修改后的請求方法
export function remoteApi(data, cancelToken) { return request({ url: '/api', method: 'post', cancelToken, data }) }
實際請求時,創(chuàng)建cacelToken:
// 組件方法內(nèi) this.cancelToken = CancelToken.source() remoreApi(data, this.cancelToken).then(....).catch(....).finally(....)
需要取消請求時,執(zhí)行:
// 組件方法內(nèi) this.cancelToken.cancel('取消下載')
避免重復(fù)請求
避免一個接口的重復(fù)請求,以免延時長的接口返回數(shù)據(jù)覆蓋另一個接口的返回數(shù)據(jù),造成數(shù)據(jù)顯示錯誤。思路也相對簡單,使用一個全局Map存儲請求標(biāo)識與對應(yīng)的cancelToken。請求,在發(fā)起請求前,按照請求標(biāo)識,喚起對應(yīng)cancelToken的cancel方法,然后再發(fā)出新請求,即可滿足條件。
總結(jié)
到此這篇關(guān)于axios取消請求與避免重復(fù)請求的文章就介紹到這了,更多相關(guān)axios取消請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
antd vue表格可編輯單元格以及求和實現(xiàn)方式
這篇文章主要介紹了antd vue表格可編輯單元格以及求和實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04前端實現(xiàn)簡單的sse封裝方式(React hook Vue3)
這篇文章主要介紹了前端實現(xiàn)簡單的sse封裝方式(React hook Vue3),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08