axios請(qǐng)求中斷的幾種方法
背景
在實(shí)際應(yīng)用場(chǎng)景中,假如有一個(gè)下載或者導(dǎo)出請(qǐng)求,數(shù)據(jù)量非常大的情況下,接口響應(yīng)的會(huì)很慢,這時(shí)候我我們想中斷請(qǐng)求,該怎么做呢?
我們先來(lái)看一下axios官方給出的請(qǐng)求中斷的方法 AXios請(qǐng)求中斷 axios中文網(wǎng)
方法一:傳入cancelToken
傳入cancelToken,在頁(yè)面調(diào)用request.cancel('中斷請(qǐng)求')
api請(qǐng)求代碼: axios代碼封裝request.js
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
const service = axios.create({
baseURL: process.env.VUE_APP_API,
timeout: 1800000
})
// 請(qǐng)求攔截
service.interceptors.request.use(
config => {
if (store.getters.token) {
config.headers['Authorization'] = getToken()
}
return config
},
error => {
return Promise.reject(error)
}
)
// 響應(yīng)攔截
service.interceptors.response.use(
response => {
const res = response.data
if (!res.status && response.status === 200) {
return response
}
if (res.status !== '200') {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000,
dangerouslyUseHTMLString: true
})
if (res.status === '401') {
MessageBox.confirm('訪問(wèn)了未授權(quán)的資源或者登入狀態(tài)已失效,你可以繼續(xù)留在這個(gè)頁(yè)面,或者重新登入', '是否重新登入', {
confirmButtonText: '重新登入',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 清空Token,并且重新登入
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
if (error.response && error.response.status === 401) {
MessageBox.confirm('提示', '是否重新登入', {
confirmButtonText: '重新登入',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 清空Token,并且重新登入
store.dispatch('user/resetToken').then(() => {
location.reload()
})
}
return true
} else if (error.response && error.response.status === 502) {
Message({
message: '502 系統(tǒng)正在重新發(fā)布中,請(qǐng)稍后再試',
type: 'error',
duration: 5 * 1000
})
} else if (error.response && error.response.status === 404) {
Message({
message: '404 系統(tǒng)正在重新發(fā)布中或請(qǐng)求不存在,請(qǐng)稍后再試',
type: 'error',
duration: 5 * 1000
})
} else {
Message({
message: error.message,
type: 'error',
duration: 5 * 1000,
dangerouslyUseHTMLString: true
})
}
return Promise.reject(error)
}
)
// api.js
import request from '@/utils/request'
// 這是一個(gè)導(dǎo)出接口
export function export(data, cancelToken) {
return request({
url: '/order/order-export',
method: 'post',
responseType: 'blob',
data,
cancelToken
})
在頁(yè)面中調(diào)用接口
<button @click='exportData'>導(dǎo)出</button>
<button @click='handleCancel'>取消</button>
import {export} from '@/api.js'
import axios from 'axios'
data() {
return {
request:null
}
}
methods:{
// 導(dǎo)出
exportData() {
const request = axios.CancelToken.source()
this.request = request
export({},request.token)
.then(res => {})
.catch((err) => {})
},
//取消
handleCancel () {
this.request.cancel('中斷請(qǐng)求')
}
}
方法二:AbortController
此方法必須要求axios的版本最低是V0.22.0,否則不生效 還是上面的代碼,做以下修改:
// api.js
export function exportData(data) {
return request({
url: '/order/order-export',
method: 'post',
responseType: 'blob',
data,
signal: data.signal // 新加的代碼
})
}
// 頁(yè)面中使用
import {export} from '@/api.js'
import axios from 'axios'
let controller;
methods:{
// 導(dǎo)出
exportData() {
controller = new AbortController()
export({singal:controller.singal}).then(res => {
console.log('下載成功')
})
.catch((err) => {
if (axios.isCancel(err)) {
console.log('下載被取消')
} else if (err.name === 'AbortError') {
console.log('下載被中止')
} else {
console.error(`下載錯(cuò)誤:${err.message}`)
}
})
},
//取消
handleCancel () {
if (controller) {
controller.abort() // 使用 abort 方法中止下載 console.log('中止導(dǎo)出')
}
}
}
多個(gè)請(qǐng)求的取消
此方法利用 fetch API 方式—— AbortController 取消請(qǐng)求:
首先要對(duì)request.js的封裝做出修改
// 取消請(qǐng)求
export const abortRequest = (controller) => {
if (controller) {
controller.abort()
}
}
// 請(qǐng)求攔截
service.interceptors.request.use(
(config) => {
if (config.abortController) {
config.signal = config.abortController.signal
}
...其他代碼跟上面一樣
return config
})
// api.js
export function download(data, abortController) {
return request({
url: '/order/order-download',
method: 'POST',
responseType: 'blob',
data,
abortController // 新加的代碼
})
}
export function exportData(data,abortController) {
return request({
url: '/order/order-export',
method: 'post',
responseType: 'blob',
data,
abortController // 新加的代碼
})
}
在頁(yè)面中使用
<div>
<button @click="fetchData1">發(fā)起請(qǐng)求 1</button>
<button @click="abortDownload1">中止請(qǐng)求 1</button>
<button @click="fetchData2">發(fā)起請(qǐng)求 2</button>
<button @click="abortDownload2">中止請(qǐng)求 2</button>
</div>
let controller1;
let controller2;
import {abortRequest} from '@/utils/request.js'
import {exportData,downLoad} from '@/api'
methods:{
// 取消請(qǐng)求1
abortDownload1() {
abortRequest(controller1)
}
// 取消請(qǐng)求2
abortDownload2() {
abortRequest(controller2)
}
// 發(fā)起請(qǐng)求1
fetchData1() {
controller1 = new AbortController()
const abortController = controller1
exportData(data,abortController).then(res => {
console.log('成功')
})
.catch(err => {
if (axios.isCancel(err)) {
console.log('下載被取消')
common.showMessage(this, '到導(dǎo)出取消', 'warning')
} else if (err.name === 'AbortError') {
console.log('下載被中止')
} else {
console.error(`下載錯(cuò)誤:${err.message}`)
}
})
},
fetchData2() {
controller2 = new AbortController()
const abortController = controller2
download(data,abortController).then(res => {
console.log('成功')
})
.catch(err => {
if (axios.isCancel(err)) {
console.log('下載被取消')
common.showMessage(this, '到導(dǎo)出取消', 'warning')
} else if (err.name === 'AbortError') {
console.log('下載被中止')
} else {
console.error(`下載錯(cuò)誤:${err.message}`)
}
})
},
}
到此這篇關(guān)于axios請(qǐng)求中斷的幾種方法的文章就介紹到這了,更多相關(guān)axios請(qǐng)求中斷內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決vue+element 鍵盤(pán)回車(chē)事件導(dǎo)致頁(yè)面刷新的問(wèn)題
今天小編就為大家分享一篇解決vue+element 鍵盤(pán)回車(chē)事件導(dǎo)致頁(yè)面刷新的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
Vue中mixins的使用方法以及實(shí)際項(xiàng)目應(yīng)用指南
vue中提供了一種混合機(jī)制--mixins,用來(lái)更高效的實(shí)現(xiàn)組件內(nèi)容的復(fù)用,下面這篇文章主要給大家介紹了關(guān)于Vue中mixins的使用方法以及實(shí)際項(xiàng)目應(yīng)用指南,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03
如何利用Vue3管理系統(tǒng)實(shí)現(xiàn)動(dòng)態(tài)路由和動(dòng)態(tài)側(cè)邊菜單欄
通常我們?cè)趘ue項(xiàng)目中都是前端配置好路由的,但在一些項(xiàng)目中我們可能會(huì)遇到權(quán)限控制,這樣我們就涉及到動(dòng)態(tài)路由的設(shè)置了,下面這篇文章主要給大家介紹了關(guān)于如何利用Vue3管理系統(tǒng)實(shí)現(xiàn)動(dòng)態(tài)路由和動(dòng)態(tài)側(cè)邊菜單欄的相關(guān)資料,需要的朋友可以參考下2022-02-02
深入學(xué)習(xí)Vue nextTick的用法及原理
這篇文章主要介紹了深入學(xué)習(xí)Vue nextTick的用法及原理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
Vue加載組件、動(dòng)態(tài)加載組件的幾種方式
組件是Vue.js最強(qiáng)大的功能之一。組件可以擴(kuò)展HTML元素,封裝可重用的代碼。這篇文章通過(guò)實(shí)例代碼給大家介紹了Vue加載組件、動(dòng)態(tài)加載組件的幾種方式,需要的朋友參考下吧2018-08-08
Vue+Elementui el-tree樹(shù)只能選擇子節(jié)點(diǎn)并且支持檢索功能
這篇文章給大家介紹了Vue+Element UI el-tree樹(shù)只能選擇子節(jié)點(diǎn)并且支持檢索的文章,通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-12-12
vue-loader和webpack項(xiàng)目配置及npm錯(cuò)誤問(wèn)題的解決
這篇文章主要介紹了vue-loader和webpack項(xiàng)目配置及npm錯(cuò)誤問(wèn)題的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07

