Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
Axios: method is called before interceptor

I am trying to update access token using refresh tokens. I am using axios interceptors to call the /refreshendpoint which returns a new access token. I am setting the token and refresh token in local storage. however, when the token is expired, the getAll method is called before the response interceptor. the token does get updated in the local storage after I call the /refresh endpoint in the response interceptor, but in the getAll method, the token that's set in the header is still the previous expired token. When I refresh the page though, the new token is set in the header and it works as expected. when I see the server console, it shows the /patients endpoint is called before the /refresh endpoint. I am calling the getAll method when the component mounts.

axios interceptor code:

import { getFromLS } from "./localStorage";

const baseURL = "http://localhost:4200/api" 
const instance = axios.create({
  baseURL,
});

instance.interceptors.request.use((request: AxiosRequestConfig) => {
  axios.defaults.headers.common["Authorization"] = "";
  delete axios.defaults.headers.common["Authorization"];
  if (getFromLS("token")) {
    if(request.headers) {
      request.headers.Authorization = getFromLS("token");
    }
  }
  return request;
});

instance.interceptors.response.use(
  (response) => response,
  (error) => {
    const originalRequest = error.config;

    if (
      error.response.status === 401 &&
      originalRequest.url === `${baseURL}/refresh`
    ) {
      return Promise.reject(error);
    }

    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      instance
        .post("/refresh", {
          body: {
            id: Number(getFromLS("user")),
            refreshToken: getFromLS("refreshToken"),
          },
        })
        .then((response) => {
          const newToken = response.data.data.newAccessToken;
          localStorage.setItem("token", newToken);
          instance.defaults.headers.common[
            "Authorization"
          ] = `Bearer ${newToken}`;
          return instance(originalRequest);
        })
    }
    return Promise.reject(error);
  }
);

export default instance;

the getAll method which uses the above axios instance:

 get: (url: string) => instance.get<IPatientResponse>(url).then(responseBody)
 getAll: (): Promise<IPatientResponse[]> => get("/patients"),
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda