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);
}
}
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?
So I found the solution to my question, hopefully this will help others with the same problem. It turns out I was setting withCredentials
incorrectly and should be set as follows:
@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);
}
}
When it is set like this, angular will automatically find the associated cookies and send them with the request
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With