1

У меня возникли проблемы с работой в Aurelia.Восстановление маршрутов после обновления

Когда пользователь переходит к моему приложению, если у них есть , прошедший проверку подлинности, я хочу перенаправить их на целевую страницу. Если нет, перейдите на страницу входа.

У меня есть аутентифицированный пользователь, перенаправляющий рабочий тон (app.js -> login.js -> setupnav.js -> целевая страница).

У меня проблема сейчас:

  • Когда пользователь обновляет страницу (http://localhost:8088/aurelia-app/#/landing), то landing маршрут больше не существует, и выдается ошибка в консоли (ERROR [app-router] Error: Route not found: /landing(…)). Я бы хотел направить пользователя на login, если маршрут не найден.

Кто-нибудь знает, как я могу перенаправить пользователя от отсутствующего пути к моей login странице?

Также любые комментарии о том, как я настроил маршрутизацию, приветствуются.

app.js

import {inject} from 'aurelia-framework'; 
import {Router} from 'aurelia-router'; 
import {FetchConfig} from 'aurelia-auth'; 
import {AuthorizeStep} from 'aurelia-auth'; 
import {AuthService} from 'aurelia-auth'; 

@inject(Router,FetchConfig, AuthService) 
export class App { 

    constructor(router, fetchConfig, authService){ 
     this.router = router; 
     this.fetchConfig = fetchConfig; 
     this.auth = authService; 
    } 

    configureRouter(config, router){ 
     config.title = 'VDC Portal'; 
     config.addPipelineStep('authorize', AuthorizeStep); // Add a route filter to the authorize extensibility point. 
     config.map([ 
      { route: ['','login'], name: 'login',  moduleId: './login',  nav: false, title:'Login' }, 
      { route: '', redirect: "login" }, 
      { route: 'setupnav', name: 'setupnav',  moduleId: './setupnav', nav: false, title:'setupnav' , auth:true} 

     ]); 
     this.router = router; 

    } 

    activate(){ 
     this.fetchConfig.configure(); 
    } 

    created(owningView: View, myView: View, router){ 
     /* Fails to redirect user 
     if(this.auth.isAuthenticated()){ 
      console.log("App.js ConfigureRouter: User already authenticated.."); 
      this.router.navigate("setupnav"); 
     } 
     */ 
    } 
} 

login.js

import {AuthService} from 'aurelia-auth'; 
import {inject} from 'aurelia-framework'; 
import {Router} from 'aurelia-router'; 
@inject(AuthService, Router) 

export class Login{ 
    constructor(auth, router){ 
     this.auth = auth; 
     this.router = router; 

     if(this.auth.isAuthenticated()){ 
      console.log("Login.js ConfigureRouter: User already authenticated.."); 
      this.router.navigate("setupnav"); 
     } 
    }; 

    heading = 'Login'; 

    email=''; 
    password=''; 
    login(){ 
     console.log("Login()..."); 

     return this.auth.login(this.email, this.password) 
     .then(response=>{ 
      console.log("success logged"); 
      console.log(response); 
     }) 
     .catch(err=>{ 
      console.log("login failure"); 
     }); 
    }; 
} 

Перенаправление на:

setupnav.js

import {Router} from 'aurelia-router'; 
import {inject} from 'aurelia-framework'; 

@inject(Router) 
export class Setupnav{ 

    theRouter = null; 

    constructor(router){ 
     console.log("build setupnav. router:" + this.theRouter); 
     this.theRouter = router 
    }; 

    activate() 
    {  
     this.theRouter.addRoute({ route: 'landing', name: 'landing', moduleId: 'landing', nav: true, title:'Integration Health' , auth:true}); 
     this.theRouter.addRoute({ route: 'tools', name: 'tools', moduleId: 'tools', nav: true, title:'Integration Tools' , auth:true}); 
     this.theRouter.refreshNavigation(); 
     this.theRouter.navigate("landing"); 
    } 
} 

ответ

2

Чтобы отобразить неизвестный маршрут на конкретную страницу , используйтеособенности:

configureRouter(config, router) { 
    ... 
    config.mapUnknownRoutes(instruction => { 
    return 'login'; 
    }); 
} 

Тем не менее, это может быть легче держать все авторизовать из связанной логики из маршрутизации и вместо того, чтобы использовать setRoot установить соответствующий модуль корня в зависимости от состояния Идента пользователя.

Стандартный main.js выглядит следующим образом:

main.js

export function configure(aurelia) { 
    aurelia.use 
    .standardConfiguration() 
    .developmentLogging(); 

    aurelia.start().then(a => a.setRoot()); 
} 

Вы можете изменить логику на что-то вроде этого:

main.js

export function configure(aurelia) { 
    aurelia.use 
    .standardConfiguration() 
    .developmentLogging(); 

    aurelia.start().then(() => { 
    if (userIsAuthenticated) { 
     return aurelia.setRoot('app'); 
    } 
    if (userPreviouslyAuthenticated) { 
     return aurelia.setRoot('login'); 
    } 
    return aurelia.setRoot('landing'); 
    }); 
} 

В приведенном выше примере модуль app является единственным модулем, который будет настраивать маршруты. Модуль login будет страницей входа в систему, которая называется setRoot('app') после того, как пользователь был успешно зарегистрирован. Страница landing вызовет setRoot('login'), когда пользователь нажмет на ссылку/кнопку.

Вот ответ на связанный с этим вопрос, что может быть полезно: https://stackoverflow.com/a/33458652/725866

+0

'config.mapUnknownRoutes' было именно то, что я искал, спасибо! Я использую плагин [aurelia-auth] (https://github.com/paulvanbladel/aurelia-auth), поэтому я не думаю, что могу использовать его в 'main.js' .. – TomSelleck

+0

вам следует изменить' router .navigate ('login'); 'to' return 'login'; 'или вы получите сообщение об ошибке в консоли. Я попытался отредактировать ваш пост, но он был отклонен: P – TomSelleck

+0

Я думаю, что он был отклонен, потому что в вашем редактировании есть опечатка. Позвольте мне посмотреть, смогу ли я это исправить. –