当前位置:网站首页>请求/响应拦截器写法
请求/响应拦截器写法
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
边栏推荐
- LeetCode 387. 字符串中的第一个唯一字符
- II. Binary tree to Offer 68 - recent common ancestor
- PMP 80个输入输出总结
- Immutable
- FFmpeg 搭建本地屏幕录制环境
- typescript28 - value of enumeration type and data enumeration
- 万字逐行解析与实现Transformer,并进行德译英实战(二)
- typescript24 - type inference
- 报错:AttributeError: module ‘matplotlib’ has no attribute ‘figure’
- 律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性
猜你喜欢
pytroch、tensorflow对比学习—使用GPU训练模型
[target detection] YOLOv7 theoretical introduction + practical test
深圳某游戏研发公司给每个工位都装监控,网友:堪比坐牢!
程序员代码面试指南 CD15 生成窗口最大值数组
状态压缩dp
II. Binary tree to Offer 68 - recent common ancestor
剑指 Offer 68 - II. 二叉树的最近公共祖先
MySQL-DML语言-数据库操作语言-insert-update-delete-truncate
typescript26-字面量类型
可持久化线段树
随机推荐
UE4 从鼠标位置射出射线检测
Excuse me, only primary key columns can be queried using sql in table storage. Does ots sql not support non-primary keys?
6-23漏洞利用-postgresql代码执行利用
状态压缩dp
万字逐行解析与实现Transformer,并进行德译英实战(一)
LeetCode 387. 字符串中的第一个唯一字符
The difference between scheduleWithFixedDelay and scheduleAtFixedRate
【愚公系列】2022年07月 Go教学课程 024-函数
剑指 Offer 68 - II. 二叉树的最近公共祖先
How to promote new products online?
25. Have you been asked these three common interview questions?
typescript22-接口继承
High Numbers | 【Re-integration】Line Area Score 880 Examples
y83. Chapter 4 Prometheus Factory Monitoring System and Actual Combat -- Advanced Prometheus Alarm Mechanism (14)
在互联网时代,有诸多「互联网+」模式的诞生
【无标题】
56:第五章:开发admin管理服务:9:开发【文件上传到,MongoDB的GridFS中,接口】;(把文件上传到GridFS的SOP)
MySQL-DML语言-数据库操作语言-insert-update-delete-truncate
Mysql基础篇(约束)
typescript27-枚举类型呢