Created
March 30, 2019 07:33
-
-
Save cxmokai/fc3f196ddf79384b697a014245708530 to your computer and use it in GitHub Desktop.
axios configs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import axios from 'axios'; | |
| import { Message } from 'element-ui'; | |
| import store from './store'; | |
| import { router } from './router'; | |
| if (process.env.NODE_ENV === 'production') { | |
| axios.defaults.baseURL = ''; | |
| } else { | |
| axios.defaults.baseURL = ''; | |
| } | |
| function showErrorMessage(message) { | |
| Message.error({ showClose: true, message: message }); | |
| } | |
| axios.interceptors.request.use((config) => { | |
| store.addLoadingRef(); | |
| // set token | |
| if (localStorage.getItem('...')) { | |
| config.headers['...'] = localStorage.getItem('...'); | |
| } | |
| return config; | |
| }, (error) => { | |
| if (process.env.NODE_ENV !== 'production') { | |
| // eslint-disable-next-line | |
| console.log(error); | |
| } | |
| return Promise.reject(error); | |
| }); | |
| axios.interceptors.response.use((response) => { | |
| store.minusLoadingRef(); | |
| if (process.env.NODE_ENV !== 'production') { | |
| // eslint-disable-next-line | |
| console.log(response); | |
| } | |
| const { data } = response; | |
| if (data.code !== 0) { | |
| showErrorMessage(`${data.msg} ${data.code}`); | |
| // remove token | |
| if (data.code === ...) { | |
| localStorage.removeItem('...'); | |
| router.push({ name: 'login' }); | |
| } | |
| return Promise.reject(data); | |
| } | |
| return data.data; | |
| }, (error) => { | |
| store.minusLoadingRef(); | |
| if (process.env.NODE_ENV !== 'production') { | |
| // eslint-disable-next-line | |
| console.log(JSON.stringify(error)); | |
| } | |
| if (error.response) { | |
| const message = 'Server Exception'; | |
| showErrorMessage(`${message} ${error.response.status}`); | |
| } else if (error.request) { | |
| showErrorMessage(error.request); | |
| } else { | |
| showErrorMessage(error.message); | |
| } | |
| return Promise.reject(error); | |
| }); | |
| export default axios; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment