配置角度项目以在开发模式下发送http cookie

时间:2018-10-18 19:24:23

标签: angular

我已经编写了一个PHP后端,用于检查请求是否来自授权用户。只需使用以下代码即可完成

if(!isset($_SESSION["id"])){
    http_response_code(403);
    die("Error. Unauthorized user.");  
}

这在生产中完全可以,但是在开发中我遇到了问题,因为在本地开发服务器上运行的角度应用程序不会发送cookie(服务器也不会存储cookie)。

如何在开发过程中配置角度服务器/应用程序以发送会话cookie?我正在使用以下代码来启动应用程序

ng serve --port 4000 --host example.com --ssl true --sslKey path --sslCert path2

更新

我不想更改我的应用逻辑或其他任何内容。这是使开发易于管理的方法。我需要在ng serve发送cookie或将节点服务器配置为在其运行时发送cookie。另外,如果在生产中使用一个版本,而在开发中使用另一个版本(如强制暗示的答案所示),则每次推送更新时我都需要对其进行更改,然后再将其更改回去,剩下两个版本。糟糕的做法

更新2:

有关其他答案,请参见以下问答:sending cookies in Angular app and Access-Control-Allow-Origin in development mode

1 个答案:

答案 0 :(得分:2)

在每个请求上传递cookie非常简单。 ng serve没有提供启用此功能的方法,但是您可以根据环境设置有条件地传递cookie:

这是一个示例拦截器:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { environment } from '@app/environments/environment.ts'

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {

  intercept (httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = httpRequest.clone({
      withCredentials: environment.sendCookies,
    });

    return next.handle(clonedRequest);
  }

}

在您的environment.ts中,您可以将sendCookies设置为true,在environment.prod.ts中,将其设置为false。这样,您仍然只有一个版本的应用程序,但是在需要的地方却有不同的行为。