创建loading.js文件
import {
Loading
} from 'element-ui';
let loadingCount = 0;
let loading;
const startLoading = () => {
loading = Loading.service({
lock:false,
spinner:'el-icon-loading',
background:'rgba(0,0,0,.5)',
text:'数据加载中,请稍后。。。'
});
};
const endLoading = () => {
loading.close();
};
export const showLoading = () => {
startLoading();
};
export const hideLoading = () => {
endLoading();
};
拦截器文件
import axios from "axios"
import {showLoading, hideLoading } from '@/utils/loading';
//相关的api接口
const request = axios.create({
baseURL: '/api',
timeout: 20000, // 请求超时时间
showLoading: true // 请求接口附加参数,打开遮罩层
});
// 请求拦截器
request.interceptors.request.use(config=>{
if (config.showLoading == true) {
showLoading()
}
if(localStorage.getItem("token")){ //如果token存在
config.headers["Authorization"] = localStorage.getItem("token")
}
return config
}, error => {
hideLoading();
console.log(error)
Promise.reject(error)
})
//获取后端给我们的数据做一个响应后拦截操作
request.interceptors.response.use(res=>{
hideLoading();
// 未设置状态码则默认成功状态
const code = res.status || 200;
// 截取code开头数字
const codeSub = res.status.toString().substr(0, 1)
// 判断code是几位数
const codeLength = res.status.toString()
// 获取错误信息
const msg = errorCode[code] || res.data.message || errorCode['default'] // errorCode文件可以封装一些常见错误状态码
if (code === 401) {
MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.href = '/index';
})
})
} else if (code === 500) {
MessageBox.alert(msg, '错误提示', {
dangerouslyUseHTMLString: true,
confirmButtonText: '确定',
type: 'error',
callback: action => {
}
});
} else if (codeSub == 5 && codeLength.length == 4) {
return res.data
} else if (code === 304) {//自定义错误状态码
return res.data
} else if (code !== 200) {
Message({
message: msg,
type: 'error'
})
return Promise.reject('error')
} else {
return res.data
}
},
error => {
hideLoading();
console.log('err' + error)
let { message } = error;
if (message == "Network Error") {
message = "后端接口连接异常";
}
else if (message.includes("timeout")) {
message = "系统接口请求超时";
}
else if (message.includes("Request failed with status code")) {
message = "系统接口" + message.substr(message.length - 3) + "异常";
}
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
})
export {request}
封装常见错误状态码文件errorCode.js
export default {
'401': '认证失败,无法访问系统资源',
'403': '当前操作没有权限',
'404': '访问资源不存在',
'default': '系统未知错误,请反馈给管理员'
}
标签:遮罩,code,const,res,element,ui,error,message,else
From: https://www.cnblogs.com/axingya/p/17846998.html