Skip to content

Instantly share code, notes, and snippets.

@34fame
Created September 4, 2020 00:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 34fame/4ee83460189cd8dccd2a40f261b0cdb0 to your computer and use it in GitHub Desktop.
Save 34fame/4ee83460189cd8dccd2a40f261b0cdb0 to your computer and use it in GitHub Desktop.
Quasar Boot File for Axios
import Vue from 'vue'
import axios from 'axios'
const instance = axios.create({})
instance.defaults.baseURL = process.env.API_BASEURL
instance.defaults.headers.common['Accept'] = 'application/json'
instance.defaults.headers.common['X-RequesterId'] = 'unknown'
instance.defaults.headers.post['Content-Type'] = 'application/json'
instance.defaults.headers.patch['Content-Type'] = 'application/json'
instance.interceptors.request.use(function (config) {
Vue.$log.debug('axios', 'request', config.method.toUpperCase() + ' ' + config.url)
if (config.headers.common) Vue.$log.debug('axios', 'request', 'headers-common', config.headers.common)
if (config.headers[config.method]) Vue.$log.debug('axios', 'request', 'headers-method', config.headers[config.method])
if (config.data) Vue.$log.debug('axios', 'request', 'data', config.data)
return config
}, function (error) {
Vue.$log.error('axios', 'request', 'error', error)
return error
})
instance.interceptors.response.use(function (response) {
Vue.$log.debug('axios', 'response', response.status + ' ' + response.statusText)
if (response.headers) Vue.$log.debug('axios', 'response', 'headers', response.headers)
if (response.data) Vue.$log.debug('axios', 'response', 'data', response.data)
return response
}, function (error) {
Vue.$log.error('axios', 'response', 'error', error)
return error
})
export { instance }
@34fame
Copy link
Author

34fame commented Sep 4, 2020

After doing some trial and error I've come up with this axios config for Quasar. I like that I can set all of my defaults here (even separated by method). I also setup interceptors on request and response so that every call can be logged (based on log levels). I'm really happy with it! I'm using vuejs-logger for logging.

To use anywhere in your project:

import { instance as axios} from 'boot/axios'
...
   let url = '/foo/bar'
   try {
      let result = await axios.get(url)
      return result
   } catch (err) {
      return err
   }
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment