For now I have this piece of code
import addToast from '@/utils/toast-queue';
import routes from './routes';
import App from './app';
import './assets/styles/global.scss';
import { jsonRequest } from './utils/requests';
Vue.use(VueRouter);
const router = new VueRouter({ routes });
router.beforeEach(async (to, from, next) => {
const userInfo = await jsonRequest('GET', '/user/info');
const notAuthenticated = userInfo.status !== 200;
if (to.name !== 'login' && notAuthenticated) {
if (to.name === 'survey') {
next({ name: 'survey' });
} else {
addToast('Please login', { type: 'error' });
next({ name: 'login' });
}
} else {
next();
}
});
/* eslint-disable-next-line no-new */
new Vue({
el: '#app',
router,
render: h => h(App)
});
When a GET request comes from /user/info to the path /public/form I would like an user not authenticated to be redirected to the page displaying the form. How can I achieve this in vue.js?
I have declared the route in route.js file like this
{
path: '/public/form',
name: 'form',
component: () => import('./views/form'),
}
I updated the beforeEach() like this
router.beforeEach(async (to, from, next) => {
const userInfo = await jsonRequest('GET', '/user/info');
const notAuthenticated = userInfo.status !== 200;
if (to.name !== 'login' && notAuthenticated) {
if (to.name === 'form') {
next({ name: 'form' });
} else {
addToast('Please login', { type: 'error' });
next({ name: 'login' });
}
} else {
next();
}
});
but it seems not working
According to the documentation, you should use
return { name: 'Login' };
or
return '/login';
instead of
next({ name: 'login' });
The same for form.