当前位置:网站首页>请求/响应拦截器写法
请求/响应拦截器写法
2022-08-01 04:58:00 【tingkeiii】
写请求拦截器、响应拦截器的request.js内容如下:
import axios from 'axios'
import { getToken ,removeToken} from '@/utils/auth.js'
// 按需引入element的消息弹窗
import {Message,MessageBox} from 'element-ui'
//配置请求的基础url以及响应超时时间
axios.defaults.baseURL = '请求的公共地址'
axios.defaults.timeout = 30 * 1000
//请求拦截器,在请求头里添加TOKEN
axios.interceptors.request.use(config => {
if(getToken()) {
// 配置请求头的token授权
config.headers.Authorization = getToken()
}
// 必须要返回config
return config
},
//参数二,对错误请求做什么
error => {
console.log('请求出错,错误是' + error)
//返回一个失败状态promise
return Promise.reject(error)
},
)
//响应拦截器,对于响应过滤
axios.interceptors.response.use(res => {
// 获取到状态码
const status = res.data.meta.status
//获取响应提示信息
const msg = res.data.meta.msg
//状态码401,说明需要用户重新登陆授权
if (status === 401) {
MessageBox('登陆已过期,请重新登陆', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}).then(() => {
// 重新登陆之前需要:1.清除cookies中的token 2.跳转登录页 3.刷新页面以清空vuex数据
if(getToken()){
removeToken();
}
this.$router.push({ path: '/login' })
location.reload()
})
}
// 响应的结果有报错
else if (status !== 200) {
Message.error(msg)
// 返回一个失败状态的promise
return Promise.reject('出错了')
}
// 若正常响应,则返回响应结果
else {
Message({
message: msg,
type: 'success',
})
return res.data
}
},
//没网,不能成功发起请求
()=>{
Message({
message: '请检查网络!',
type: 'error',
})
return Promise.reject('出错了')
})
// 一定要返回实例
export default axios
边栏推荐
猜你喜欢
随机推荐
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
The method of solving stored procedure table name passing through variable in mysql
lambda
LeetCode 27. 移除元素
干货!如何使用仪表构造SRv6-TE性能测试环境
【目标检测】YOLOv7理论简介+实践测试
(2022 Niu Ke Duo School IV) N-Particle Arts (Thinking)
(2022牛客多校四)D-Jobs (Easy Version)(三维前缀或)
(2022 Nioke Duo School IV) D-Jobs (Easy Version) (3D prefix or)
typescript19-对象可选参数
typescript24 - type inference
II. Binary tree to Offer 68 - recent common ancestor
请问shake数据库中为什么读取100个collection 后,直接就退出了,不继续读了呢?
PMP 项目沟通管理
【愚公系列】2022年07月 .NET架构班 085-微服务专题 Abp vNext微服务网关
The difference between scheduleWithFixedDelay and scheduleAtFixedRate
出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
pytorch、tensorflow对比学习—功能组件(激活函数、模型层、损失函数)
李迟2022年7月工作生活总结