Search code examples
vue.jsaxiosvuexnuxt.js

Nuxt axios interceptors not logging as expected


I have created an axios.js file as per the documentation to extend axios as I want to trigger a loader every time a request is made:

export default function({ $axios, store }) {
  console.log(store)
  // request
  $axios.onRequest((config) => {
    console.log('request')
  })

  // response
  $axios.onResponse((res) => {
    console.log('response')
  })

  // error
  $axios.onError((config) => {
    console.log('error')
  })
}

However nothing is being logged in the browser when a request is made. Not sure what I am doing wrong but when I add interceptors directly to the axios object it is fine. I am not sure how to commit an action when doing that though.

I have added the plugin like so:

/*
   ** Plugins to load before mounting the App
   */
  plugins: ['@/plugins/filters.js', './plugins/axios.js'],

filters is working as expected

I am using middleware to send an action:

export default function({ store }) {
  return store.dispatch('getProducts')
}

And the action uses axios:

import axios from 'axios'

const actions = {
  async getProducts({ commit }) {
    try {
      const result = await axios.get(`${process.env.browserBaseUrl}`)
      commit('getProducts', result.data.quotes)
    } catch (e) {
      console.error(e)
    } finally {
      console.log('We do cleanup here')
    }
  },
  setCurrentFilter({ commit }, payload) {
    commit('setCurrentFilter', payload)
  }
}

export default actions

Solution

  • You don't need to import if axios is already registered as plugin. You can use axios like this - this.$axios.$get('url', ()=> {}). Maybe that's why it is happening.