1.请求拦截器
这个拦截器会在你发送请求之前运行
应用场景(验证token过期):每一次请求去判断是否有token,如果token存在则在请求头加上这个token。后台会判断这个token是否过期。
import axios from 'axios'
var newAxios = axios.create({
baseURL: '/api', // 代理名
timeout: 10000, // 请求超时事件
crossDomain: true
})
// 请求拦截器
newAxios.interceptors.request.use(
(config)=>{
console.log('请求拦截器1 成功')
return config
},
(error)=>{
console.log('请求拦截器1 失败')
return Promise.reject(error)
}
)
export default newAxios
2.响应拦截器
import axios from 'axios'
var newAxios = axios.create({
baseURL: '/api', // 代理名
timeout: 10000, // 请求超时事件
crossDomain: true
})
newAxios.interceptors.response.use(
(response) => {
console.log('响应拦截器 成功')
return response
},
(error)=>{
console.log('响应拦截器 失败')
return Promise.reject(error)
}
)
export default newAxios
3.取消请求(有坑)
(1).引入axios —— 不要 create axios实例
import Vue from 'vue'
import App from './App.vue'
// 千万不要用 axios.create 出来的实例,因为他没有 axios.CancelToken 构造函数
import axios from 'axios'
// 配置默认路径
axios.defaults.baseURL = '/api'
// 将axios挂载到Vue上
Vue.prototype.axios = axios
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
(2).发送/取消请求
<template>
<div id="app">
<button @click="sendAjax">发送请求</button>
<br>
<br>
<button @click="cancelAjax">取消请求</button>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
cancel:''
}
},
methods:{
sendAjax(){
this.axios({
url:'/hello',
// 添加一个配置项,接收取消请求的函数
cancelToken:new this.axios.CancelToken((c)=>{
this.cancel = c
})
}).then(res=>{
console.log('请求成功',res)
}).catch((err)=>{ // 这里一定要接 .catch 不然会报错
console.log(err)
})
},
cancelAjax(){
// 判断 当前是不是有请求正在发送
if(typeof this.cancel === 'function'){
this.cancel('请求被强制取消了')
}
}
}
}
</script>