I have my API hosted on a different url than the web applications that will access it. I currently have CORS configured to allow everything in my API's Startup:
ConfigureServices:
services.AddCors(options => {
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
Configure:
app.UseCors("CorsPolicy");
app.UseMvc();
If I type the API URL into the browser it returns the request fine and get my data back as expected.
But when I attempt to make that API call with javascript as follows:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/Controller');
xhr.onload = function () {
if (xhr.status === 200) {
alert('Response is ' + xhr.responseText);
console.log('Response is ' + xhr.responseText);
}
else {
alert('Request failed. Returned status of ' + xhr.status);
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
It fails and I get the following error message in my console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the
remote resource at https://api.example.com/Controller. (Reason: CORS header
‘Access-Control-Allow-Origin’ missing).[Learn More]
What am I missing here, what needs to be tweaked to make this work?