I am doing a Vue project. Right now I'm handling authentication via JWT. To do so, I am creating a module "axios.js" that should be imported into main.js to allow for token validation and therefore give permissions to users.
The main idea is to pass a token to an endpoint /endpoint
and have it return the status code.
My current problem is that I am not being able to return the status code, I'm getting a Promise and not the boolean.
auth.js
import axios from "axios";
var config = {
headers: { Authorization: "Bearer " + localStorage.getItem("usertoken") }
};
export default async function isAuth() {
let responseStatus = axios.get("http://localhost:5000/endpoint", config);
let status = await responseStatus.then(res => {
if (res.status == 200) {
return true;
} else {
return false;
}
});
return status;
}
The relevant part of the main.js file is below. The rest are imports and routes, which probably are not necessary here.
main.js
import isAuth from "./axios/auth.js";
const router = new VueRouter({
mode: "history",
routes
});
router.beforeEach((to, from, next) => {
// eslint-disable-next-line no-console
console.log(isAuth());
var requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (requiresAuth && !isAuth()) {
next("/login");
} else if (to.path == "/login" && isAuth()) {
next("/home");
} else {
next();
}
});
Find the print screen with the console.log(isAuth())
on the main.js below:
Please let me know if more information is necessary! Thank you.