Created
April 11, 2023 12:48
-
-
Save nidbCN/062b4903c5b93e45f85b9c6cdff434e6 to your computer and use it in GitHub Desktop.
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 { getToken } from '@/utils/auth' | |
| // create an axios instance | |
| const service = axios.create({ | |
| baseURL: 'http://localhost:8887', | |
| // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url | |
| // withCredentials: true, // send cookies when cross-domain requests | |
| timeout: 5000 // request timeout | |
| }) | |
| // request interceptor | |
| service.interceptors.request.use( | |
| config => { | |
| // do something before request is sent | |
| if (store.getters.token) { | |
| // let each request carry token | |
| // ['X-Token'] is a custom headers key | |
| // please modify it according to the actual situation | |
| config.headers['token'] = getToken() | |
| config.headers['Authorization'] = 'restaurant_' + getToken() | |
| } | |
| return config | |
| }, | |
| error => { | |
| // do something with request error | |
| console.log(error) // for debug | |
| return Promise.reject(error) | |
| } | |
| ) | |
| // response interceptor | |
| service.interceptors.response.use( | |
| /** | |
| * If you want to get http information such as headers or status | |
| * Please return response => response | |
| */ | |
| /** | |
| * Determine the request status by custom code | |
| * Here is just an example | |
| * You can also judge the status by HTTP Status Code | |
| */ | |
| response => { | |
| const res = response | |
| if (res.headers['Content-Type'] === 'application/json') { | |
| if (!res.data['flag']) { | |
| res.data = { flag: false, message: '请求出错' } | |
| } | |
| } | |
| // if the custom code is not 20000, it is judged as an error. | |
| return res | |
| }, | |
| error => { | |
| console.log('err' + error) // for debug | |
| Message({ | |
| message: error.message, | |
| type: 'error', | |
| duration: 5 * 1000 | |
| }) | |
| return Promise.reject(error) | |
| } | |
| ) | |
| export default service |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment