简体   繁体   English

Angular 2 + Heroku,始终重定向到https://而不是使用http://

[英]Angular 2+Heroku , always redirect to https:// instead of using http://

I have an application of Angular 2 hosted in Heroku, I would like to redirect all http requests to https, what would be the correct way to do it? 我在Heroku中托管了Angular 2的应用程序,我想将所有http请求重定向到https,正确的方法是什么? Thank you! 谢谢!

If you wish to redirect any URL to its https equivalent, implement this class as a service. 如果您希望将任何URL重定向到其等效的https,请将该类实现为服务。 The class checks for developer mode so that redirect will only happen when the app is deployed in 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;
  }

}

This guard must be applied to every path. 此防护措施必须应用于所有路径。 For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM