Skip to content

Instantly share code, notes, and snippets.

@d1y
Created April 30, 2020 06:09
Show Gist options
  • Select an option

  • Save d1y/07d32f9431f565e95a508576ef742005 to your computer and use it in GitHub Desktop.

Select an option

Save d1y/07d32f9431f565e95a508576ef742005 to your computer and use it in GitHub Desktop.
axios拦截器
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