首页 > 解决方案 > 不能同时使用 HttpHeaders 和 WithCredentials 选项

问题描述

我有一个 .net5 WebApi,它需要从我的 Angular 应用程序发送凭据。当我使用 HttpInterceptor 指定我的所有请求将在每次调用中包含凭据时,一切都很好,但是如果我将withCredentials选项与任何HtpHeaders请求放在一起,则不会通过 CORS 验证。

这是我的拦截器的样子(工作正常):

@Injectable({ providedIn: 'root' })
export class HttpInterceptService implements HttpInterceptor {

  constructor() { }

  public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request.clone({
      withCredentials: true
    }));
  }
}

但如果调用如下,CORS 验证不会通过:

public apiCall(): Observable<any> {
  return this.httpClient.get(API_URL, {
    withCredentials: true,
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      Authorization: 'my-auth-token'
    })
  });
}

CORS 错误(当我将 withCredentials 与标头一起使用时):

CORS 错误

但是,如果我删除标题,一切正常:

public apiCall(): Observable<any> {
  return this.httpClient.get(API_URL, {
    withCredentials: true
  });
}

标签: angularangular-httpclient

解决方案


推荐阅读