前端排位日记
作者:互联网
axios请求拦截统一后端返回错误代码
src文件同级新建http.js文件
内容如下:
import axios from 'axios'
import { Message, Loading } from 'element-ui';
import router from './router'
axios.defaults.baseURL = process.env.API_ROOT;
axios.interceptors.request.use(config => {
let token = localStorage.getItem("authorization")
if (token) {
config.headers.Authorization = token
}
return config;
}, err => {
Message.error({ message: '请求超时!' });
return Promise.resolve(err);
})
axios.interceptors.response.use(res => {
if (res.config.responseType == "blob") {
return res;
}
if (res.data.code == 200) {
return res;
} else if (res.data.code == 401) {
router.push('/login')
//实现登录过期校验
} else if (res.data.code == 400) {
Message.error({ message: res.data.message, duration: 4000 });
return Promise.reject(res);
} else if (res.data.code == 500) {
Message.error({ message: res.data.message, duration: 4000 });
// console.log( res.data.message);
return Promise.reject(res);
}
Message.error({ message: res.data.message, duration: 4000 });
return Promise.reject(res);
},, err => {
if (err.response.status == 504 || err.response.status == 500) {
Message.error({ message: '服务器出错', duration: 4000 });
} else if (err.response.status == 403) {
Message.error({ message: '权限不足,请联系管理员!', duration: 4000 });
} else if (err.response.status == 404) {
Message.error({ message: '404,找不到地址!', duration: 4000 });
} else if (err.response.status == 401) {
router.push('/login')
} else if (err.response.status == 502) {
console.log("502错误")
} else {
Message.error({ message: '未知错误', duration: 4000 });
}
return Promise.reject(err);
})
export default axios
//具体内容可以根据需求自定义
标签:return,err,res,前端,else,Message,排位,message,日记 来源: https://blog.csdn.net/alfar6054/article/details/121014235