Gosch
Gosch

Reputation: 33

Axios interceptor with axios helper

I'm building an application with vuejs, nuxt and axios and I'm trying to make a plugin with axios interceptor and axios helper like this:

Individually they work as expected but with both together, for some reason, will always call only the helper, meaning that only the third console.log will be displayed. But the helper is only for errors and none of the requests failed. So what is causing this and why the first or second console.log not being displayed.

Upvotes: 0

Views: 4551

Answers (2)

Dev.DY
Dev.DY

Reputation: 455

When defining the interceptor of the axios in the $axios context, you can define the "request" and "response" interceptors just like "onError".

// axios plugin

export default function ({$axios}) {
    // request
    $axios.onRequest(config => {
        // ...
    })

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

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

The nuxt module is a simplified re-defined axios module.

Upvotes: 2

ssc-hrep3
ssc-hrep3

Reputation: 16069

You can use an axios response interceptor to catch your errors. In the documentation, you'll find everything you need to globally catch REST errors.

Here is an example using response interceptors combined with request interceptors with your console.log() statements:

axios.interceptors.request.use(function (config) {
  console.log(1);
  return config;
}, function (error) {
  console.log(2);
  return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  console.log(3);
  return Promise.reject(error);
});

Upvotes: 0

Related Questions