vue防⽌接⼝重复请求实现⽅法// 封装axios的请求,返回重新封装的数据格式
// 对错误的统⼀处理
import axios from 'axios'
import errorHandle from './errorHandle'
const CancelToken = axios.CancelToken
class HttpRequest {
constructor (baseUrl) {
this.baseUrl = baseUrl
this.pending = {} // 对象的key为每个正在请求的接⼝,value为取消该接⼝的⽅法
}
// 获取axios配置
getInsideConfig () {
const config = {
baseURL: this.baseUrl,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
timeout: 10000
}
pending
return config
}
removePending (key, isRequest = false) {
/
/ 同⼀接⼝重复请求
if (this.pending[key] && isRequest) {
this.pending[key]('取消重复请求')
}
// 如果不是同⼀接⼝重复请求,则删除pending对象⾥该请求对应的key
delete this.pending[key]
}
// 设定
interceptors (instance) {
// 请求
quest.use((config) => {
/
/ Do something before request is sent
let key = config.url + '&' + hod
config.cancelToken = new CancelToken((c) => {
this.pending[key] = c
})
return config
}, (err) => {
// debugger
errorHandle(err)
// Do something with request error
ject(err)
})
// 响应请求的
sponse.use((res) => {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
let key = fig.url + '&' + hod
// 响应结束后删除pending对象⾥该请求对应的key
if (res.status === 200) {
solve(res.data)
} else {
ject(res)
}
}, (err) => {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
// debugger
errorHandle(err)
ject(err)
})
}
/
/ 创建实例
request (options) {
const instance = ate()
const newOptions = Object.InsideConfig(), options)
this.interceptors(instance)
return instance(newOptions)
}
get (url, config) {
const options = Object.assign({
method: 'get',
url: url
}, config)
quest(options)  }
post (url, data) {
quest({
method: 'post',
url: url,
data: data
})
}
}
export default HttpRequest

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。