Timing (async) problem with vue-router guard and loaded user roles using axios while starting the app for the first time
-
Hi,
My app doesn’t have a login page. Login is done by an external service. So when my Quasar app starts (for the first time), I call an endpoint to fetch the user roles (this is done in a boot file using axios).
The problem is that the vue-router guard have to check the user roles to grant or deny access, for example:
... beforeEnter: (to, from, next) => { if (account.state.roles.includes('ADMIN')) { next() return } next('/forbidden') }
But when the app is started for the first time, the roles are not loaded yet. This means, that the user will be ‘redirected’ to the forbidden page.
Because the axios call is asynchronous the roles will be available after the vue-router beforeEnter method is executed.
Is there a way to ensure that the axios call is done before the vue-router method is executed? Or is there a different (better) approach for that? I just want to make sure that the user roles are loaded before the Quasar app is started (or at least the vue-router method is executed).
I appreciate your help. Thanks!
Daniel -
So, don’t make the loading of the roles async. Make it synchronous.
Scott
-
@s-molinari I already tried this, but with no luck. How can I do this? My boot file looks like this:
axios .get('https://URL/token') .then(response => { // here I have my roles })
So, how can I make the axios call synchronous?
-
Did you make the boot file function async?
Scott
-
why don’t you make your boot file function async then do
try{ let response=await axios.get('https://URL/token'); }catch(...){ ... }
-
@s-molinari Thank you so much. This helped!
-
@walfin Thanks for your help. I changed the boot file to:
export default async ({ store, app }) => { await axios .get(...) .then(response => { ... }) }
And now it’s working as expected.
-
@daniel Just FYI, you don’t have to use then() when you’re using await (it converts the resolved value to the return value).