Is there a way to successfully redirect using an axios interceptor?

In my Vue.js project (main.js), I implemented an axios interceptor for handling refresh tokens. The goal is to automatically get a new token using the refresh_token when a 401 error status code is received, and then retry the failed request with the new token. However, if the refresh token itself is invalid, I need to redirect the user to the login page and stop any further axios requests.

Unfortunately, I encountered two issues. Firstly, when the refresh token is invalid, the application gets stuck in a loop of making repeated API calls to refresh the token, resulting in multiple "duplicate navigation" errors in the console. Secondly, I am unable to properly catch the error in the catch block as the execution always falls into the then block, leading to an undefined response.

axios.interceptors.response.use((response) => {
        return response
    },
    function (error) {
        const originalRequest = error.config;
        if (error.response.status === 401) {
            axios.post(process.env.VUE_APP_BASE_URL + process.env.VUE_APP_REFRESH_TOKEN,
                {
                    "refresh_token": localStorage.getItem("refresh_token")
                })
                .then(res => {
                        localStorage.setItem("token", "Bearer " + res.data.result.access_token);
                        originalRequest.headers['Authorization'] = localStorage.getItem("token");
                        return axios(originalRequest);
                }).catch(error=>{
                    console.log(error);
                    router.push({'name':'login'})
            })
        }
    });

Answer №1

If you want to enhance security, consider incorporating a flag into your code. Here's an example:

let has401Error = false;
axios.interceptors.response.use((response) => {
        return response;
    },
    function (error) {
        const originalRequest = error.config;
        if (!has401Error && error.response.status === 401) {
            has401Error = true;
            axios.post(process.env.VUE_APP_BASE_URL + process.env.VUE_APP_REFRESH_TOKEN,
                {
                    "refresh_token": localStorage.getItem("refresh_token")
                })
                .then(res => {
                        localStorage.setItem("token", "Bearer " + res.data.result.access_token);
                        originalRequest.headers['Authorization'] = localStorage.getItem("token");
                        return axios(originalRequest);
                }).catch(error => {
                    console.log(error);
                    router.push({'name':'login'});
                    has401Error = false;
            });
        }
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I would greatly appreciate any recommendations on how to troubleshoot and

I've been working on the "Map the Debris" challenge at freecodecamp, and I'm facing an issue. While my code works fine in my PC's editor, it doesn't satisfy the conditions when I paste it into the website area. Any suggestions on how t ...

D3 not distinguishing between bars with identical data even when a key function is implemented

When attempting to create a Bar chart with mouseover and mouseout events on the bars using scaleBand(), I encountered an issue. After reviewing the solution here, which explains how ordinal scale treats repeated values as the same, I added a key to the dat ...

What is the process for eliminating the invocation of a function in Jquery?

I am currently facing an issue with my application. When I launch the Ficha() function, it initiates an ajax call and works perfectly fine. However, another ajax call is made later to load HTML tags that also need to invoke the Ficha() function. The prob ...

It is impossible to remove or trim line endings with regex in Node.JS

I'm having trouble with using process and util in a NodeJS script. Even after trimming, line breaks persist in the resulting string (as seen in the console.log() output below). I'm unsure why this is happening. var util = require("util"); proces ...

Implementing a technique to synchronize table updates with only new or modified data using jQuery and ajax

Just diving into the world of jQuery! Currently, I have a table set up to load data from the server using ajax\jQuery every x seconds. The data is being received in JSON format. My main challenge right now is figuring out how to update only specific ...

Guide to creating a nested object using React Hooks

I am currently developing a form that includes a section where users can select the quantity and category of concert tickets from a dropdown menu. This dynamic component allows for multiple items with different quantities and categories. The dropdown categ ...

Using JSON within a GraphQL type definition in a Node.js environment

Utilizing Node.js, I am making requests to a report API that returns JSON responses. The API accepts different IDs as parameters, resulting in varying responses. For instance: https://report.domain.io/report/1 https://report.domain.io/report/2 Each r ...

Angular's UI router is directing users to the incorrect URL

Just starting out with Angular 1 and tasked with adding a new feature to an existing webapp. The webapp utilizes jhipster for backend and frontend generation (Angular 1 and uirouter). I attempted to create my own route and state by borrowing from existing ...

Verify image loading using jQuery

<img src="newimage.jpg" alt="thumbnail" /> I am dynamically updating the src attribute of this image. Is there a way to verify if the image has been successfully loaded and take action once it is? Appreciate any guidance on this matter. ...

Oops! Looks like we couldn't locate the request token in the session when attempting to access the Twitter API

Every time I attempt to connect to the Twitter API using Passport OAuth, an issue arises that redirects me to an error page displaying this message: Error: Failed to locate request token in session at SessionStore.get (/Users/youcefchergui/Work/ESP/socialb ...

Passing a function into the compile method in AngularJS: A comprehensive guide

I have created a directive called pagedownAdmin with some functionality to enhance the page editor: app.directive('pagedownAdmin', ['$compile', '$timeout', function ($compile, $timeout) { // Directive logic here... }]); ...

Experimenting with a sophisticated AngularJS component (dynamic menu that expands automatically)

My menu project built with AngularJS is quite complex, and I need help on testing it. The testing framework being used is Jasmine and Karma. Most of the resources available online only cover basic directives and controllers. You can view the project runni ...

What is the main object used in a module in Node.js for global execution?

Node.js operates on the concept of local scope for each module, meaning variables defined within a module do not automatically become global unless explicitly exported. One question that arises is where a variable declared in a module file belongs in term ...

An issue arises when attempting to execute npm with React JS

I encountered an error after following the setup steps for a react configuration. Can anyone provide assistance? This is the content of the webpack.config.js file: var config = { entry: './main.js', output: { path:'/', ...

Is it possible to modify the text depending on the chosen option from the dropdown menu

When a user selects "First Name" from a select box, I want the placeholder text 'Enter your First Name' to appear next to the textbox. Below is a snippet of my code: HTML: <select id="selectionType"> <option value="-1">Select One< ...

I am attempting to transfer information from one page to another in Next.js, but unfortunately, I am experiencing difficulties in

Encountering the following error message: "Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead." Any assistance will be greatly appreciated. export default func ...

The screen suddenly goes blank when attempting to load a Google Charts example using XMLHttpRequest

I'm currently working on a page that utilizes the XMLHttpRequests to avoid reloading the entire page. Once the user logs in, it should display a chart. You can find the main page here: http://pastebin.com/h55Vzuvy And this is the chart we are trying t ...

Async Autocomplete fails to display options if the label keys do not match the filtering keys

While I have experience with ReactJs and Material UI, I encountered a surprising issue. I am using the Material-UI Autocomplete component as shown below. The users variable is an array of objects. When searching for firstName or lastName in the user table, ...

Function activated when adding an event listener

Retrieve information from page.html: <div id="46" class="cont-text-profile"> <span class="data"># March 4, 2021, 5:17 p.m.</span> <p class="text">Tutto ok!!!!!!!111111111222222233333334444444& ...

Exploring the functionalities of the execPopulate() method

I'm hitting a roadblock with using execPopulate. I've gone through the documentation, but it's just not clicking for me. Could someone clarify when exactly execPopulate() should be used after populate() and when it's unnecessary? In s ...