My Nodejs restful service has the following endpoint http://localhost:3000/api/countries. I am using this middleware https://github.com/expressjs/cors. I have cors enabled thus:-
const cors = require('cors');
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
I have the following code in my Angular 6 app hosted at http://localhost:4200
import { HttpClient, HttpHeaders } from '@angular/common/http';
httpClient: HttpClient;
getCountries(): Observable<any> {
const url = 'http://localhost:3000/api/countries';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
})
};
return this.httpClient.get(url, httpOptions).pipe(
map((result: any) => {
return result;
})
);
}
I have the following code in my React App at http://localhost:3001
getCountries() {
const url = 'http://localhost:3000/api/countries';
const init = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
try {
const response = await fetch(url, init);
const json = await response.json();
return json
};
}
My react code works perfectly giving the desired response, but the Angular 6 gives the following error:-
Access to XMLHttpRequest at 'http://localhost:3000/api/countries' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
What am I doing wrong in my angular 6 code?
Please note that I have seen answers to similar questions suggesting using a json file (proxy.conf.json) to act as a proxy server or install a chrome extension. These are not options for me.
Thanks in advance of your helpful responses.