当前位置:网站首页>请求/响应拦截器写法
请求/响应拦截器写法
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
边栏推荐
猜你喜欢
Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
今日睡眠质量记录68分
Risk strategy important steps of tuning method
华为Android开发面试后得出的面试秘诀
typescript21 - Comparison of Interfaces and Type Aliases
认真对待每一个时刻
The difference between scheduleWithFixedDelay and scheduleAtFixedRate
Mysql基础篇(约束)
PAT乙级 1002 写出这个数
初识shell脚本
随机推荐
华为Android开发面试后得出的面试秘诀
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
(Codeforce 757)E. Bash Plays with Functions(积性函数)
IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints
scheduleWithFixedDelay和scheduleAtFixedRate的区别
状态压缩dp
pytroch、tensorflow对比学习—搭建模型范式(低阶、中阶、高阶API示例)
Visual Studio提供的 Command Prompt 到底有啥用
Code Interview Guide for Programmers CD15 Generating an Array of Windowed Maximums
风险策略调优中重要的三步分析法
typescript20-接口
typescript26 - literal types
Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
博客系统(完整版)
Excuse me, only primary key columns can be queried using sql in table storage. Does ots sql not support non-primary keys?
Swastika line-by-line parsing and realization of the Transformer, and German translation practice (2)
Mysql基础篇(约束)
Immutable
(2022 Nioke Duo School IV) H-Wall Builder II (Thinking)
MySQL-数据定义语言-DDLdatebase define language