CORS not working properly for domain and subdomain. I've a single NodeJS server hosted at https://api.example.com I've two ReactJS Clients
Client 1. https://example.com
Client 2. https://subdomain.example.com
I've configured Client 1 to force www so that a single origin is used for Client 1. When I open Clien1 that works fine. When I open Client2 I get the error that
Access to XMLHttpRequest at 'https://api.example.com/someAPI' from origin 'https://subdomain.example.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://www.example.com' that is not equal to the supplied origin
When I press Ctrl+F5 then it works fine but after that If I refresh Client1 then the error comes at Client1
Access to XMLHttpRequest at 'https://api.example.com/someAPI' from origin 'https://www.example.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://subdomain.example.com' that is not equal to the supplied origin.
Now When I press Ctrl+F5 at Client1 then it works fine but the same error goes to the Client2.
My nodeJS server is configured as follows
var whitelist = ['https://www.example.com', 'https://subdomain.example.com'];
getCorsCoptions(req, callback) {
var getOriginValue = () => {
if (whitelist.indexOf(req.header('origin')) !== -1) {
return true;
} else {
log.error(__filename, 'Not allowed by CORS', origin);
return false;
}
}
var corsOptions = {
origin: getOriginValue(),
methods: ['GET', 'POST'],
credentials: true,
preflightContinue: false,,
allowedHeaders:["Content-Type","X-Requested-With","X-HTTP-Method-Override","Accept"]
}
callback(null, corsOptions)
}
app.use('*', cors(this.getCorsCoptions));
app.options('*', cors(this.getCorsCoptions));
I'm using axios at React Client sides as follows
get(url: string) {
return Axios.get(url, {
withCredentials: true
}).then((res: any) => {
if (res) {
return res.data;
}
return {};
});
}
post(url: string, data: any) {
let requestHeaders = { 'Content-Type': 'application/json' };
return Axios.post(url, data, {
headers: requestHeaders
, withCredentials: true
}).then((res: any) => {
if (res) {
return res.data;
}
return {};
});
}