当前位置:网站首页>请求/响应拦截器写法
请求/响应拦截器写法
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
边栏推荐
- pytroch、tensorflow对比学习—搭建模型范式(构建模型方法、训练模型范式)
- 怀念故乡的面条
- Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
- The difference between scheduleWithFixedDelay and scheduleAtFixedRate
- typescript27 - what about enumeration types
- y83.第四章 Prometheus大厂监控体系及实战 -- prometheus告警机制进阶(十四)
- 数组问题之《下一个排列》、《旋转图像》以及二分查找之《搜索二维矩阵》
- 李迟2022年7月工作生活总结
- (2022 Niu Ke Duo School IV) K-NIO's Sword (Thinking)
- pytorch、tensorflow对比学习—张量
猜你喜欢
6-23漏洞利用-postgresql代码执行利用
pytroch、tensorflow对比学习—搭建模型范式(低阶、中阶、高阶API示例)
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
API Design Notes: The pimpl trick
High Numbers | 【Re-integration】Line Area Score 880 Examples
时时刻刻保持敬畏之心
mysql中解决存储过程表名通过变量传递的方法
typescript27 - what about enumeration types
数组问题之《下一个排列》、《旋转图像》以及二分查找之《搜索二维矩阵》
(2022 Nioke Duo School IV) D-Jobs (Easy Version) (3D prefix or)
随机推荐
可持久化线段树
25. 这三道常见的面试题,你有被问过吗?
RSA主要攻击方法
typescript25-类型断言
y83. Chapter 4 Prometheus Factory Monitoring System and Actual Combat -- Advanced Prometheus Alarm Mechanism (14)
TIM登陆时提示00001(TIM00001)
剑指 Offer 68 - II. 二叉树的最近公共祖先
项目风险管理必备内容总结
程序员代码面试指南 CD15 生成窗口最大值数组
ModuleNotFoundError: No module named 'tensorflow.keras' error message solution
ModuleNotFoundError: No module named ‘tensorflow.keras‘报错信息的解决方法
Dynamic Programming 01 Backpack
PMP 80个输入输出总结
备战金九银十,如何顺利通过互联网大厂Android的笔面试?
请问表格储存中用sql只能查询到主键列,ots sql非主键不支持吗?
【愚公系列】2022年07月 Go教学课程 024-函数
数据比对功能调研总结
出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
Power button (LeetCode) 212. The word search II (2022.07.31)
PAT乙级 1002 写出这个数