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?
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