-1

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:

console log

Please let me know if more information is necessary! Thank you.

Mario
  • 4,784
  • 3
  • 34
  • 50
rgpereira
  • 3
  • 4
  • Hello @TylerRoper and thanks for the quick answer! I'm trying to use `.then()` as suggested in there but seems like I'm not able to return the `true` or `false` from the `isAuth()` function. – rgpereira Dec 27 '19 at 18:26

1 Answers1

0

Axios.get already returns a promise, so you can just return axios.get(...) from your isAuth function. Then, where you're consuming the isAuth function, you can run isAuth().then(...) or use async/await by doing await isAuth();

import isAuth from './axios/auth.js'

var config = {
  headers: {
    'Authorization': "Bearer " + localStorage.getItem('usertoken')
  }
};

export default async function isAuth() {
  // Axios.get already returns a promise, so just return Axios.get
  return axios.get("http://localhost:5000/endpoint", config);
}


const router = new VueRouter({
  mode: 'history',
  routes
})


router.beforeEach((to, from, next) => {
  // eslint-disable-next-line no-console
  console.log(isAuth()) // This will just log a Promise.
  var requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  isAuth().then(result => {
    if (result) {
      // result success
    } else {
      // result fail
    }
  });
});


// Or, with async/await

router.beforeEach(async(to, from, next) => {
  // eslint-disable-next-line no-console
  console.log(isAuth()) // This will just log a Promise.
  var requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const isAuthed = await isAuth();
  if (isAuthed) {
    // result success
  } else {
    // result fail
  }
});

Also, note that Promises also have a .catch function for error handling. You may want to add that so you can handle any exceptions returned by the endpoint.

mwilson
  • 12,295
  • 7
  • 55
  • 95