Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!