Home > front end >  React refresh token interceptor
React refresh token interceptor

Time:10-24

I have a problem with refreshing a token. After I updated the token, a request should be made with my configurations, but this does not happen. The token is updated, but the second time the getIserInfo method is executed, it does not work.

My axios interceptors:

import axios from "axios";
import {getToken, logOut, refreshToken, setUser} from "@/services/auth.service";

const HTTP = axios.create({baseURL: process.env.REACT_APP_API_ENDPOINT});

HTTP.interceptors.request.use(
    config => {
        const token = getToken();

        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }

        return config;
    },
    error => Promise.reject(error)
)

HTTP.interceptors.response.use(
    response => response,
    async error => {
        debugger;
        const originalRequest = error.config;

        if (error.response.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true;

            try {
                const response = await refreshToken();
                const {data} = await response;

                setUser(data);
            } catch (e) {
                logOut();
            }

            return HTTP(originalRequest);
        }

        return Promise.reject(error);
    }
)

export default HTTP

After executing the token, the getUserInfo method should have worked again

enter image description here

Works after removing headers

delete originalRequest["headers"]

return HTTP(originalRequest);

CodePudding user response:

The problem was in axios 1.0 . After removing and switching to version 0.27, everything worked. It's most likely a bug on their part.

  • Related