Angular Refused to set unsafe header “Cookie” in REST-call

I need to set header “Cookie” in my REST-call to server, but get Refused to set unsafe header “Cookie” in my browser.
Can anyone please help me with how to get around this problem in Angular.

  public getData(): Observable<any> {
    const httpHeaders = new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Cookie', 'access_token=eyJh...');

    return this.http.get<any>(`/v1/getData`, {
      headers: httpHeaders,
      withCredentials: true
    });
  }

In the browser, you cant manually set the Cookie header due to security reasons. Instead, cookies are handled automatically by the browser.

If you want to send cookies with your request in Angular, you only need to set the withCredentials property to true.

public getData(): Observable<any> {
  const httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');

  return this.http.get<any>(`/v1/getData`, {
    headers: httpHeaders,
    withCredentials: true
  });
}

Make sure that the server is set up to handle CORS and accept credentials if it’s a cross-origin request.

Leave a Comment