import axios from "axios" import router from '@/router/routers' import { Notification } from 'element-ui' //elementUI 提示框组件 import store from '../store' import { getToken } from '@/utils/auth' import Config from '@/settings' import Cookies from "js-cookie" //创建axios 实例 const service = axios.create({ //api 的 base_url在.env.development有配置 baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : '/', //请求超时时间 timeout: Config.timeout }) //添加请求拦截器 service.interceptors.request.use( // 在发送请求之前做些什么 config => { //如果获取token if (getToken()) { //每次请求都附带上header的Authorization config.headers['Authorization'] = getToken() } //请求格式 config.headers['Content-Type'] = 'application/json' return config }, error => { //对请求错误的处理 Promise.reject(error) } ) //添加响应拦截器 service.interceptors.response.use( //响应后要做的事情 response => { //返回响应数据 return response.data }, //响应错误处理 error => { //兼容blob下载出错json提示 if (error.response.data instanceof Blob && error.response.data.type.toLowerCase().indexOf('json') !== -1) { //创建文件读取对象 const reader = new FileReader() //读取指定的Blob中错误信息内容 reader.readAsText(error.response.data, 'utf-8') //读取文件完成后触发onload事件 reader.onload = function (e) { //转换错误信息 const errorMsg = JSON.parse(reader.result).message //通知提醒框返回错误信息 Notification.error({ title: errorMsg, duration: 5000 }) } } else { let code = 0 //捕获错误信息 try { //获取响应错误状态码 code = error.response.data.status } catch (e) { //做请求超时判断 if (error.toString().indexOf('Error:timeout') !== -1) { Notification.error({ title: '网络请求超时', duration: 5000 }) //拿到回调信息并返回 return Promise.reject(error) } } console.log(code) //错误代码判断 if (code) { if (code === 401) { //跳转401并写入Cookies store.dispatch('LogOut').then(() => { // 用户登录界面提示 Cookies.set('point', 401) //重新加载 location.reload() }) } else if (code === 403) { //如果是403直接返回401页面路径 router.push({ path: '/401' }) } else { //获取错误信息 const errorMsg = error.response.data.message if (errorMsg !== undefined) { //告知提示框错误信息 Notification.error({ title: errorMsg, duration: 5000 }) } } } else { //否则把请求接口失败告知提示框 Notification.error({ title: '接口请求失败', duration: 5000 }) } } //返回错误 return Promise.reject(error) } ) export default service