import Vue from 'vue' import axios from 'axios' import { Message } from 'element-ui' import store from '../store/index' import { getToken } from '@/utils/auth' // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8' axios.defaults.baseURL = (process.env.VUE_APP_ISPROXY * 1 ? '' : '') + '/api' axios.defaults.timeout = 20000 axios.interceptors.request.use(config => { if (getToken()) { config.headers['token'] = getToken() } if (config.method === 'post') { config.params = undefined } return config }, error => Promise.resolve(error.response || error) ) axios.interceptors.response.use(response => { if (response.data && response.data.code !== 200 && response.data.msg) { Message.error(response.data.msg) } if (response.data && response.data.code === 403) { store.dispatch('user/logout') setTimeout(() => { location.href = '/login' }, 200) } return response }, error => { if (error.response && error.response.data.msg) { Message.error(error.response.data.msg) } else if (error.message) { if (error.code && error.code === 'ECONNABORTED') { Message.error('连接超时') } else { Message.error(error.message) } } return Promise.resolve(error.response || error) } ) export const fetch = (url, data = {}, method = 'post') => { return new Promise((resolve, reject) => { axios({ url, data: method === 'post' ? data : {}, params: method === 'post' ? {} : data, method }).then(res => resolve(res.data)) }) } Vue.prototype.$fetch = fetch