Axios Interceptor: return own response without making the call to the backend

134 Views Asked by At

In my axios interceptor I have a case where I have multiple cached requests in an array and I want to "answer" them with a fake response and set a custom http status message to signal the status of the request. Without this I currently get the error: "TypeError: response is undefined" at the location where I sent the axios request.

let requests = [];

axios.interceptors.response.use(response => response, async error => {
    
    if (error.response.status === '4XX')
    {
        if (differentcase === true)
        {
            requests.push(error.config);
            return;
        }

        requests.push(error.config);
        let response = axios.get('http://localhost:8888/api/data')
        if (response.data == false)
        {
            for (let i = 0; i < requests.length; i++)
            {
                //this is how I wish it worked:
                //requests[i].statusCode = XXX
                //axios.sendFakeResponse(requests[i])
            }
        }
    }
}

As the request canceling is depricated I already tried the signal with the AbortController to abort the execution of the request but this does not work:


let requests = [];
const controller = new AbortController();

axios.interceptors.response.use(response => response, async error => {
    if (error.response.status === '4XX')
    {
        if (differentcase === true)
        {
            error.config.signal = controller.signal;
            requests.push(error.config);
            return;
        }

        requests.push(error.config);
        let response = axios.get('http://localhost:8888/api/data')
        if (response.data == false)
        {
            controller.abort();
        }
    }
}
0

There are 0 best solutions below