Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

318
Vistas
How to log user out with Axios using authorization bearer + token

I have an application where I log user in by connecting to backend (using axios) and getting a JWT Token which is stored in localStorage. My problem comes in with the logout functionality. I currently do this:


async endAuth(context) {
    try {
      await axios.post("auth/logout", {
        headers: {
         Authorization:
            "Bearer " + JSON.parse(localStorage.getItem("currentUser")).token,
        },
      });
      localStorage.clear();
      context.commit("setUser", {
        token: null,
        userId: null,
      });
    } catch (e) {
      const error = new Error("Something went wrong");
      throw error;
    }
}

This does not work. The connection to API is established but i get a 401 error from backend with {success: false, message: 'Expired or Invalid Token'}

Now I tried adding "Content-Type": "application/json", to the headers still no luck.

I also changed my code to use JavaScript build in fetch() API. And that WORKS! Here is the code:

async endAuth(context) {
  let url = baseURL + "/auth/logout";
  const response = await fetch(url, {
      method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization:
        "Bearer " + JSON.parse(localStorage.getItem("currentUser")).token,
    },
    });
    const responseData = await response.json();
    if (!response.ok) {
      const error = new Error(
        responseData.message || "Failed to authenticate. Check your login data."
      );
      throw error;
    } else {
      localStorage.clear();
      context.commit("setUser", {
        token: null,
        userId: null,
      });
    }
}

I also tried setting axios headers via axios.defaults.headers.common["Authorization"] = "Bearer " + localStorage.getItem("currentUser").token; - no luck Am I missing something here with the axios request?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

General short solution:

// previus logout
this.$axios.setHeader('Authorization', `Bearer ${localStorage.getItem("token")}`);
// after logout
this.$axios.setHeader('Authorization', null)
  

Specific long solution (question):

 async endAuth(context) {
        try {
          this.$axios.setHeader('Authorization', `Bearer ${JSON.parse(localStorage.getItem("currentUser")).token}`);
          await axios.post("auth/logout");
          localStorage.clear();
          context.commit("setUser", {
            token: null,
            userId: null,
          });
          this.$axios.setHeader('Authorization', null)
        } catch (e) {
          const error = new Error("Something went wrong");
          throw error;
        }
    }

This just happened to me with nuxt, I hope someone else is useful

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda