0
votes

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.

2
Please add your code to the question. - ssc-hrep3
Btw. You could also set an interceptor to the response. This would probably solve your issue. - ssc-hrep3
I added an image there and I don't know if an interceptor for response is what I want. I think I forgot to mention but I want to validate the data of POST and PUT requests to the backend - Gosch
You should add your code always as text. Isn't a response interceptor exactly what you want to achieve with onError? Btw. onError is not in the documentation of axios. Read about the interceptors here: github.com/axios/axios#interceptors Keep also in mind, that an interceptor always handles requests and responses globally. So, if you have a validation which differs from interface to interface, you should not do that globally in an interceptor. - ssc-hrep3
That actually helped and make sense too, thanks! - Gosch

2 Answers

2
votes

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.

0
votes

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);
});