How do I enable cross domain requests using ExpressJS server and Javascript's fetch? It seems like there might be an issue with the client-side fetch()
function because the response headers include Access-Control-Allow-Origin: *
.
I attempted to resolve this by adding the following code, but it has not solved the problem:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "localhost:4200"); // update this to match the requesting domain
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Upon inspection, it appears that the request headers do not contain any information related to CORS:
Accept
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Cache-Control
max-age=0
Connection
keep-alive
Host
localhost:4200
If-None-Match
W/"2ef-TFWfb4ktmG8ds+qhoRRzEvmkPdY"
Upgrade-Insecure-Requests
1
User-Agent
Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/68.0
The frontend code snippet:
export function createHttpObservable(url: string) {
return Observable.create(observer => {
fetch(url, {mode: 'cors'})
.then(response => {
return response.json();
})
.then(body => {
observer.next(body);
observer.complete();
})
.catch(error => {
observer.error(error);
})
});
}
Error message received:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9000/api/courses. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).