tkamstra
tkamstra

Reputation: 58

VueJS - Axios Interceptors not recieving 401 response

I am trying to have a request and response interceptor setup for Axios when I make Post requests, however I can only get the request interceptor to respond, and nothing else, I've included an example of it not running:

Here is the axios setup:

import axios from "axios";

axios.defaults.baseURL = "https://btk7dl15c9.api.quickmocker.com";

axios.interceptors.request.use(
  async (config) => {
    console.log("request ok");
    return config;
  },
  (error) => {
    console.log("request error");
    return Promise.reject(error);
  }
);
axios.interceptors.response.use(
  (response) => {
    console.log("response ok");
    return response;
  },
  (error) => {
    console.log("response error");
    return Promise.reject(error);
  }
);

export default {
  methods: {
    axiosPost(url, data) {
      return axios.post(url, data);
    }
  }
};

https://codesandbox.io/s/keen-shockley-xccsx

I need to be able to intercept 401 to be able to make a token refresh call (not included with the example)

Upvotes: 3

Views: 912

Answers (2)

bumbleshoot
bumbleshoot

Reputation: 1160

For others trying to troubleshoot this problem, if the accepted answer did not work for you, check for something like this in your code:

axios.defaults.validateStatus = () => {
  return true
}

I added this to my main.js so response codes >= 300 do not throw errors. This means all responses go to the first function in my interceptor. When I moved my 401 handling to the interceptor's first function, the interceptor worked as expected.

Upvotes: 0

Tawfik Nasser
Tawfik Nasser

Reputation: 1124

You used "axios": "0.21.2" which it seems to have a bug in the interceptor that they fixed in v0.21.3

if you up to 0.21.3 or down to 0.21.1 this should fix your issue.

checkout the release log : https://github.com/axios/axios/releases/tag/0.21.3

Upvotes: 1

Related Questions