Problem with programmatic navigation in vue.js - javascript

I'm developing a Vue.js application and there is something that I can't figure out about programmatic navigation.
As you can see below in my index.js file I have a tree structured routes in my client, some of this route need to be protected.
The routes that must be protected are the ones that are child of 'dashboard'.
When the App is loaded, if the user try to navigate one of those protected routes, the client send a request to the server, asking if the token that he possess allow him to access those protected routes, if the answer is yes then the user can freely navigate, otherwise I want to redirect him to the login page.
The problem arise here, how you can see from the 'App.vue' if the request checkSession fail (meaning no valid token has been provided) the error will be catched and this.$router.push('/login') is executed, but without success, in fact the url does not change at all.
I tried to print the router object and I have noticed that the route that I'm trying to push appear under history.pending properties of the cited object.
Another weird thing that I've noticed: if I delete the redirect in the routes path (the very last one) declared in the 'index.js' file and I load the App through an url that does not belong to one of the declared routes, for example '/wrong/path', and the user does not provide a valid token then $router.push('/login') works fine.
index.js
...
const routes = [{
path: '/login',
name: 'login',
component: LoginComponent
},
{
path: '/',
name: 'dashboard',
redirect : '/dipendenti/aggiungi',
component: DashboardComponent,
children: [
{ path: 'dipendenti', component: MiddleWareComponent, children:[
{ path: 'aggiungi', component: AddWorkerComponent },
{ path: 'elimina', component: DeleteWorkerComponent },
{ path: 'modifica', component: ModifyWorkerComponent }
]},
{ path: 'clienti', component: MiddleWareComponent, children:[
{ path: 'aggiungi', component: AddClientComponent },
{ path: 'modifica', component: ModifyClientComponent }
]},
{ path: 'team', component: MiddleWareComponent, children:[
{ path: 'aggiungi', component: AddTeamComponent },
{ path: 'elimina', component: DeleteTeamComponent },
{ path: 'modifica', component: ModifyTeamComponent }
]},
{ path: 'lavori', component: MiddleWareComponent, children:[
{ path: 'visualizza', component: ViewWorkComponent },
{ path: 'aggiungi', component: AddWorkComponent },
{ path: 'elimina', component: DeleteWorkComponent },
{ path: 'modifica', component: ModifyWorkComponent }
]},
{ path: 'account', component: MiddleWareComponent, children:[
{ path: 'modifica', component: ModifyAccountComponent }
]}
]
},
{ path: '/logout', component: LogoutComponent },
{ path: '/password-forgot', component: PasswordForgotComponent },
{ path: '/password-reset/:token/:api', component: PasswordResetComponent },
{ path: '/*', redirect : '/' }
];
const router = new VueRouter({
routes: routes,
base: __dirname,
base: process.env.BASE_URL,
mode: 'history'
});
...
App.vue
<script>
import Vue from 'vue';
import axios from 'axios';
Vue.prototype.$https = axios.create({
baseURL: 'http://localhost:5000',
withCredentials: true,
crossdomain: true
});
Vue.prototype.$checkSession = function() {
if (window.location.pathname != '/login' && window.location.pathname != '/password-forgot' && window.location.pathname.split('/')[1] != 'password-reset') {
var authToken = localStorage.authToken? localStorage.authToken:sessionStorage.authToken;
this.$https.defaults.headers.common['x-csrf-token'] = authToken;
this.$https.get('api/web/user/session').then(response => {
if(window.location.pathname == '/'){
this.$router.push('/dipendenti/aggiungi');
}
}).catch(e => {
console.log(this.$router.app);
this.$router.push('/login');
})
}
}
...
export default {
name: 'app',
created: function() {
this.$checkSession();
}
};
</script>
The desired behavior would be the redirect to the login page.

Related

vue-router 4 '/:pathMatch(.*)*' not working?

hello guys I want to ask about vue-router.
when I use vue 2 if there is a page that doesn't match, I use path: '*' to go to my page404 but in vue 3 it's been replaced with '/:pathMatch(.)' after i tried it the warning in console disappeared but i just got a blank page and it doesn't point to my page404. did i miss something? I'm newbie with vue 3
here is the version I'm using:
vue: ^3.0.0
vue-router: ^4.0.0-0
and this is my index.js
import { createRouter, createWebHistory, RouterView } from 'vue-router'
const routes = [
{
path: '/',
redirect: '/login',
component: RouterView,
children: [{
path: '/login',
component: () => import('#/views/login/Login.vue'),
}]
},
{
path: '/:pathMatch(.*)*',
component: () => import('#/views/page404/Page404.vue')
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
You can try to write it like this
{
path: "/:pathMatch(.*)*",
redirect: "/404"
},
{
path: "/404",
name: "404",
component: () => import("#/views/page404/Page404.vue")
}

Rerouting sub paths to a main path in angular

In my routes file I am trying to achieve the following.
const routes: Routes = [{ ...
{ path: '', component: MainComponent, children: [
{ path: 'routeA', component: ComponentA },
{ path: 'routeA/subA', component: ComponentAA},
{ path: 'routeA/subB', component: ComponentAB},
{ path: 'routeA/**', redirectTo: 'routeA'}
]}, ...}
The intention being that routeA/ will redirect back to routeA, but the above code doesnt achieve the intended effect.

Angular Routes not mapping properly for lazy loading

So I have an app with multiple modules that has routes properly put in place, and each module has it's own routes. Everything works fine, until I try to implement lazy loading.
Previous State:
example module
export const EXAMPLE_ROUTES: Routes = [
{ path: 'new', component: AddOpportunityComponent },
{ path: ':id', component: OpportunityProfileComponent,
children: [
{
path: 'edit/sdg-info', component: SdgInfoComponent
}
]}
];
I import this EXAMPLE_ROUTES in example module
Now I have root level routing as
const APP_ROUTES: Routes = [
{ path: '', component: HomeComponent},
{ path: 'search', component: SearchComponent },
{ path: 'example', component: ExampleComponent, children: [...EXAMPLE_ROUTES], canActivate: [AuthGuard, OnboardedGuard] },
];
export const appRouting = RouterModule.forRoot(APP_ROUTES, {enableTracing: true});
With this setup it works fine
After trying to have lazy loading
example module
const EXAMPLE_ROUTES: Routes = [
{ path: 'new', component: AddOpportunityComponent },
{ path: ':id', component: OpportunityProfileComponent,
children: [
{
path: 'edit/sdg-info', component: SdgInfoComponent
}
]}
];
export const exampleRouting = RouterModule.forChild(EXAMPLE_ROUTES);
and app routing becomes
const APP_ROUTES: Routes = [
{ path: '', component: HomeComponent},
{ path: 'search', component: SearchComponent },
{ path: 'example', loadChildren: './example/example.module#ExampleModule', canActivate: [AuthGuard, OnboardedGuard] }
];
export const appRouting = RouterModule.forRoot(APP_ROUTES, {enableTracing: true});
The problem I'm facing is, the example route works fine, now the /search route breaks, as the router for some reason tries to match it with opportunity route (path: ':id')
What might be going wrong here?
This issue can occoure when you first implement your FeatureModule in your RootModule and after a given time you decide you want to load this FeatureModule lazy via loadChildren and you forgot to remove FeatureModule from your imports in your RootModule.
In your case your Routing Configuration will look something like this after compilation (PSEUDO-CODE):
const Routes_CONFIG = [
{ path: '', component: HomeComponent},
{ path: 'search', component: SearchComponent },
{ path: 'example', loadChildren: './example/example.module#ExampleModule', canActivate: [AuthGuard, OnboardedGuard] }
{ path: 'new', component: AddOpportunityComponent },
{ path: ':id', component: OpportunityProfileComponent,
children: [
{ path: 'edit/sdg-info', component: SdgInfoComponent }
]
}
]
In your case, when you just enter /search you will match :id OpportunityProfileComponent. That's because the router accepts the first route that matches a navigation request path.

Angular2 when I refresh the page, not the page loads in router params

My application loads normally in all routers but when I use
router with params the application can not loaded.
example: localhost:3000/usersid/:id
the router code is :
const appRoutes: Routes = [
{ path: 'user', component: UserComponent },
{ path: 'info', component: InfoComponent },
{ path: 'users', component: UsersComponent },
{ path: 'usersid/:id', component: UsersIdComponent },
{ path: '', component: MainComponent },
{ path: '**', component: MainComponent }
];
and the component of the params router
import{Component} from '#angular/core'
import { ActivatedRoute } from '#angular/router';
import * as Datastore from 'nedb';
#Component({
moduleId : module.id ,
templateUrl : 'userid.component.html' ,
styles : [`
.SamRouter {
overflow-y: auto;
}
`]
})
export class UsersIdComponent {
id: any;
private sub: any;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.sub = this.route.params.subscribe( params => {
// this.id = +params['id']; // (+) converts string 'id' to a number
this.id = params['id'] || 0 ;
// In a real app: dispatch action to load the details here.
});
console.log( this.id )
}
ngOnDestroy() {
// this.sub.unsubscribe();
}
}
Error Message:
http://localhost:3000/users/node_modules/bootstrap/dist/js/b‌​ootstrap.min.js
Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:3000/users/styles.css Failed to load
resource: the server responded with a status of 404 (Not Found)
It depends what server you are using.
you need to configure your server to go to index.html whenever the route is not exists.
while you press F5 the server search for a file that isn't exists, the server should return index.html and only then the angular router will do the rest.
Change this:
const appRoutes: Routes = [
{ path: 'user', component: UserComponent },
{ path: 'info', component: InfoComponent },
{ path: 'users', component: UsersComponent },
{ path: 'usersid/:id', component: UsersIdComponent },
{ path: '', component: MainComponent },
{ path: '**', component: MainComponent }
];
To this: (pay attention to the fourth element in Routes array)
const appRoutes: Routes = [
{ path: 'user', component: UserComponent },
{ path: 'info', component: InfoComponent },
{ path: 'users', component: UsersComponent },
{ path: 'users/:id', component: UsersIdComponent },
{ path: '', component: MainComponent },
{ path: '**', component: MainComponent }
];

Angular2 CanActivate guard for all routes except one

I know that we can group routes located in one module. Like that:
canActivate: [AuthGuard],
children: [
{
path: '',
children: [
{ path: 'crises', component: ManageCrisesComponent },
{ path: 'heroes', component: ManageHeroesComponent },
{ path: '', component: AdminDashboardComponent }
],
}
But I should add that guard to each module's routing file. And I have many of them.
I want that the user can not go to any route except one (login route) if he is not authorized.
What is the right way to add guard to all of them??
You can use a componentless empty path parent route with the guard
{ path: '', canActivate: [AuthGuard], children: [
{
path: '',
children: [
{ path: 'crises', component: ManageCrisesComponent },
{ path: 'heroes', component: ManageHeroesComponent },
{ path: '', component: AdminDashboardComponent }
],
}
}
and in the guard check if the user is logged in.
If not logged in and the current route is login then still allow it.

Categories

Resources