角度7:如何将http请求更改为https?我尝试使用拦截器

时间:2019-04-27 23:23:02

标签: angular angular7 interceptor angular-http-interceptors

我正在创建一个angular 7应用程序。在此应用程序中,我正在使用facebook社交登录。使用此功能时,出现控制台错误,提示我的请求应为https://请求。所以我想到了使用拦截器将http转换为https。

我创建了一个拦截器,将http请求更改为https请求,并进行了以下代码更改。

http.interceptor.ts:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent,HttpResponse }  from '@angular/common/http';
import { Observable } from 'rxjs';


@Injectable()
export class httpsInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

console.log(req.url);

const secureReq = req.clone({
  url: req.url.replace('http://', 'https://')
});     
return next.handle(secureReq);

}
}

app.module.ts:

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { httpsInterceptor } from './interceptor/https.interceptor';


providers: [
 { provide: HTTP_INTERCEPTORS, useClass: httpsInterceptor, multi: true }   
],

进行上述更改后,当我以“ ng serve”身份运行应用程序时,我可以通过http://localhost:4200访问该应用程序,但是它没有指向“ https://localhost:4200”,并且我也没有看到拦截器类的控制台日志。

当我以“ ng serve --ssl true”运行我的应用程序时,我能够通过https://localhost:4200访问该应用程序,但是当我键入http://localhost:4200时却什么也没有显示。

预期输出:

当我运行“ ng serve”并打开http://localhost:4200时,它必须重定向到https://localhost:4200

当我运行“ ng serve --ssl true”时,我也应该能够通过http://localhost:4200访问该应用程序。

请让我知道我在做错什么,还是需要再进行一些代码更改?谢谢。

0 个答案:

没有答案