在實(shí)際項(xiàng)目中,我們可能需要對請求進(jìn)行“防抖”處理。這里主要是為了阻止用戶在某些情況下短時(shí)間內(nèi)重復(fù)點(diǎn)擊某個按鈕,導(dǎo)致前端向后端重復(fù)發(fā)送多次請求,這里介紹一種使用Axios攔截器來取消重復(fù)的請求方法
import axios from 'axios'
import qs from 'qs'
import { notification, message } from 'ant-design-vue'
import router from '@/router/router'
import moment from 'moment'
import baseURL from './config'
let pending = {} // 網(wǎng)絡(luò)請求記錄
let CancelToken = axios.CancelToken
axios.defaults.timeout = 30000
axios.defaults.baseURL = baseURL.target
//設(shè)置請求攔截器
axios.interceptors.request.use(
config => {
const token = localStorage.getItem('ACCESS_TOKEN')
const companyId = localStorage.getItem('companyId')
const userId = localStorage.getItem('userId')
if (token) {
config.headers['AUTH-TOKEN'] = token
}
if (companyId) {
config.headers['companyId'] = companyId
}
if (userId) {
config.headers['userId'] = userId
}
console.log(config.url, 'config.url')
let key = `${config.url}&${config.method}&${JSON.stringify(config.data)}`
// 設(shè)置重復(fù)請求
config.cancelToken = new CancelToken(c => {
if (pending[key]) {
if (Date.now() - pending[key] > 1000) {
// 超過1s,刪除對應(yīng)的請求記錄,重新發(fā)起請求
delete pending[key]
} else {
// 1s以內(nèi)的已發(fā)起請求,取消重復(fù)請求
c('repeated')
}
}
// 記錄當(dāng)前的請求,已存在則更新時(shí)間戳
pending[key] = Date.now()
})
return config
},
error => {
return Promise.error(error)
})
// response 攔截器
axios.interceptors.response.use(
response => {
let key = `${response.config.url.replace(baseURL.target, '')}&${response.config.method}&${response.config.data}`
if (pending[key]) {
// 請求結(jié)束,刪除對應(yīng)的請求記錄
delete pending[key]
}
if (response.data.code === 101) {
localStorage.clear()
router.replace('/login')
}
if (response.data.code === 102) {
notification.error({
message: response.data.msg
})
}
if (response.data.code === 99) {
message.error(response.data.msg)
return response
}
return response
},
error => {
if (error.response) {
const data = error.response.data
const token = localStorage.getItem('ACCESS_TOKEN')
if (error.response.status === 403) {
notification.error({
message: '登錄超時(shí)',
description: data.msg
})
router.replace('/exception/403')
return
}
if (error.response.status === 404) {
notification.error({
message: '客戶端錯誤',
description: data.msg
})
router.replace('/exception/404')
return
}
if (error.response.status === 500) {
notification.error({
message: '服務(wù)器請求超時(shí)'
})
return
}
}
return Promise.reject(error)
}
)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。