Created
April 30, 2020 06:09
-
-
Save d1y/07d32f9431f565e95a508576ef742005 to your computer and use it in GitHub Desktop.
axios拦截器
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 { baseURL } from '@/config' | |
| import { getToken } from '@/lib/util' | |
| class HttpRequest { | |
| constructor (baseUrl = baseURL) { | |
| this.baseUrl = baseUrl | |
| this.queue = {} | |
| } | |
| getInsideConfig () { | |
| const config = { | |
| baseURL: this.baseUrl, | |
| headers: { | |
| // | |
| } | |
| } | |
| return config | |
| } | |
| distroy (url) { | |
| delete this.queue[url] | |
| if (!Object.keys(this.queue).length) { | |
| // Spin.hide() | |
| } | |
| } | |
| interceptors (instance, url) { | |
| instance.interceptors.request.use(config => { | |
| // 添加全局的loading... | |
| if (!Object.keys(this.queue).length) { | |
| // Spin.show() | |
| } | |
| this.queue[url] = true | |
| config.headers['Authorization'] = getToken() | |
| return config | |
| }, error => { | |
| return Promise.reject(error) | |
| }) | |
| instance.interceptors.response.use(res => { | |
| this.distroy(url) | |
| const { data } = res | |
| return data | |
| }, error => { | |
| this.distroy(url) | |
| return Promise.reject(error.response.data) | |
| }) | |
| } | |
| request (options) { | |
| const instance = axios.create() | |
| options = Object.assign(this.getInsideConfig(), options) | |
| this.interceptors(instance, options.url) | |
| return instance(options) | |
| } | |
| } | |
| export default HttpRequest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment