VUE—axios自定义请求配置—6、cancelToken取消请求
<script>
import axios from 'axios'
// 1、创建取消令牌
var CancelToken = axios.CancelToken
var source = CancelToken.source()
// axios配置
let http = axios.create({
baseURL: 'https://www.easy-mock.com/mock/5d41580a1a802c0d5e53dcc2/example/',
// 可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
// 2、配置 捕获取消错误
cancelToken: source.token
})
export default {
name: "create_cancelToken",
methods: {
postUrl () { //post方法
http.post('bb')
.then((res) => {
console.log('post请求成功', res.data)
})
.catch((err) => {
// 3、调用取消 注意:要写在catch回调函数里
if (axios.isCancel(err)) { // 用户取消
console.log(err.message) // err.message获取source.cancel中的内容
} else { // 自身原因,是否是路径出错。。或者是timeout时间太短,网速跟不上???
console.log('请求失败', err)
}
})
}
},
created () {
// 4、err.message获取的内容
source.cancel('用户取消操作啦~~~')
// 我将source.cancel放在created里,让该请求一进行时就取消,只是为了实验取消请求
// 真实项目中并不这么做
this.postUrl()
}
}
</script>