【问题标题】:Angular 2+Heroku , always redirect to https:// instead of using http://Angular 2+Heroku ,总是重定向到 https:// 而不是使用 http://
【发布时间】:2017-03-01 20:33:25
【问题描述】:

我有一个托管在 Heroku 中的 Angular 2 应用程序,我想将所有 http 请求重定向到 https,正确的方法是什么?谢谢!

【问题讨论】:

    标签: angular heroku


    【解决方案1】:

    如果您希望将任何 URL 重定向到其 https 等效项,请将此类实现为服务。该类检查开发人员模式,以便仅当应用程序部署在 prod 中时才会发生重定向。

    import {Injectable, isDevMode} from '@angular/core';
    import {CanActivate, ActivatedRouteSnapshot} from '@angular/router';
    
    @Injectable()
    export class IsSecureGuard implements CanActivate {
    
      canActivate(route: ActivatedRouteSnapshot): boolean {
        if (!(isDevMode()) && (location.protocol !== 'https:')) {
          location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
          return false;
        }
        return true;
      }
    
    }
    

    这个守卫必须应用于每条路径。例如:

     {path: 'mypath', component: MyPathComponent, canActivate: [IsSecureGuard]}
    

    【讨论】:

      猜你喜欢
      • 2016-11-15
      • 1970-01-01
      • 2021-12-12
      • 2018-01-02
      • 2014-10-07
      • 2019-06-24
      • 1970-01-01
      • 2020-06-18
      • 2019-08-04
      相关资源
      最近更新 更多