Setting a cookie header with Angular 5

Har*_*pal 3 cookies angular angular5

I'm currently attempting to set a Cookie header with the following HTTPInterceptor:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private cookieService: CookieService ) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        'Cookie': 'session=' + this.cookieService.get('session'),
        'withCredentials': 'true',
      }
    });
    return next.handle(request);
  }

}
Run Code Online (Sandbox Code Playgroud)

When attempting to set the Cookie I get the following error:

Refused to set unsafe header "Cookie"

I'm making the request to a local Flask API.

I have attempted to manually set the headers with HTTPHeaders like here and also tried to set xhr2.prototype._restrictedHeaders.cookie = false; shown here. All to no avail. Any idea how I can set the cookie?

Har*_*pal 5

所以我找到了我的问题的解决方案,希望这会帮助其他有同样问题的人。事实证明我设置withCredentials不正确,应该设置如下:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private cookieService: CookieService ) {}

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

}
Run Code Online (Sandbox Code Playgroud)

这样设置时,angular会自动查找关联的 cookie 并随请求一起发送