1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| import axios from 'axios' import Qs from 'qs' import router from '@/router' import { Message } from 'element-ui' import Cookies from 'js-cookie'
axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? '' : 'http://127.0.0.1:9999' axios.defaults.withCredentials = true axios.defaults.timeout = 1000 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.transformRequest = function (data, headers) { if (data === null || typeof data !== 'object') return data let contentType = headers['Content-Type'] || headers.post['Content-Type'] if (contentType.includes('urlencoded')) return Qs.stringify(data) if (contentType.includes('json')) return JSON.stringify(data) return data }
axios.defaults.validateStatus = function (status) { return status >= 200 && status < 400 }
axios.interceptors.request.use( config => { const token = Cookies.get('token') if (token) { config.headers['Authorization'] = token } return config }, error => { console.log(error) return Promise.reject(error) } )
axios.interceptors.response.use( response => { return response.data }, error => { if (error.message === '取消请求') return Promise.resolve('取消请求')
let response = error.response if (response) { switch (response.status) { case 401: router.push({ path: '/login' }) break case 500: router.push({ path: '/login' }) break } Message({ message: '访问失败,请联系系统管理员', type: 'warning', duration: 3 * 1000, }) } else { if (error && error.code === 'ECONNABORTED') { Message({ message: '服务器拒绝了您的请求', type: 'warning', duration: 3 * 1000, }) } if (!navigator.onLine) { Message({ message: '设备已离线', type: 'warning', duration: 3 * 1000, }) } } return Promise.reject(error) } )
export default axios
|