I have defined an http interceptor. Inside the interceptor I have the following code:
let newReq = req.clone({
withCredentials: true,
responseType: 'json'
});
Now I need to modify all requests and add an extra header Demo with the value of foo
I tried the following
let newReq = req.clone({
withCredentials: true,
responseType: 'json',
setHeaders: {'Demo' : 'foo'}
});
However I notice in the network tab that this removes almost all headers including Host & Origin from my request and it leads to CORS issues with the API that I am communicating with
Is there any way to fix this issue ? (I want to have all previous headers in my cloned request and just add a new one)
Your code seems to be working fine and and it does send the previous and new headers successfully. The culprit is the option
withCredentials: truewhich causes the following error:As the error suggests, the server is probably sending header
Access-Control-Allow-Origin: *in pre-flight check (response of OPTIONS request). Your request will only work if server sends the headerAccess-Control-Allow-Origin: http://localhost:4200 (or whatever your origin is).The reason why you cannot
Access-Control-Allow-Origin: *in combination withwithCredentials: trueis explained here: CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is trueI created a backend to reproduce this issue. Doing following steps will solve your problem:
http://localhost:4200(or your origin) to the allow CORS origin list (you cannot set it as*).access-control-allow-headersto*.allow_credentialsin your CORS settings totrue.If you are using Python (Fast API), you can do above settings like this (tested and works):
If you are using .NET Core, you can do above settings like this (not tested):
Also do similar settings on IIS (if you are using IIS).
allowCredentials="true"allowAllRequestedHeaders="true"