I am using Vue route Auth Guard with before Each function. If a user is not logged in he can not be able to access dashboard and profile page. It is working fine but when I am trying route forcefully its blocking me but also adding some extra characters in the url. Can I be able to remove those.
url - http://localhost:8080/?redirect=%2Fdashboard
import Vue from 'vue'
import Router from 'vue-router'
import * as firebase from "firebase";
Vue.use(Router)
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes : [
{
path: '/',
name: 'home',
component: () => import('../components/home')
},
{
path: '/login',
name: 'signin',
component: () => import('../components/user/signIn')
},
{
path: '/register',
name: 'signup',
component: () => import('../components/user/signUp')
},
{
path: '/forgot-password',
name: 'forgotPassword',
component: () => import('../components/user/forgotPassword')
},
{
path: '/profile',
name: 'profile',
component: () => import('../components/user/profile'),
meta: {
requiresAuth: true
}
},
{
path: '/dashboard',
name: 'dashboard',
component: () => import('../components/dashboard'),
meta: {
requiresAuth: true
}
},
]
})
//Router Guard
router.beforeEach((to, from, next) => {
// Check fore required auth guard
if(to.matched.some(record => record.meta.requiresAuth)){
// check if not logged in
if(!firebase.auth().currentUser){
// go to login
next({
path: '/',
query: {
redirect: to.fullPath
}
});
}else{
// proceed to route
next();
}
}else{
next();
}
})
export default router
When the user is not logged in, the router guard is redirecting to path: '/', query: {redirect: to.fullPath}
. At this point to.fullPath == "/dashboard"
.
The forwardslash '/'
character is not a valid query character, so vue-router converts this to the encoded version %2F
using encodeURIComponent("/dashboard")
.
When the user logs in, you can get the redirect parameter from $route.query.redirect
and it will be automatically decoded back into /dashboard
.
Alternatively, since all of your routes have names, instead of setting the redirect
parameter to to.fullPath
you could use set it to to.name
, then when the user logs in you can redirect to the route by name.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.