Currently, I am testing my ReactJS website on localhost:3333 and my ASP.NET Web API 2 on localhost:54690.
I am utilizing axios for my AJAX requests, but encountering an error when making a request.
XMLHttpRequest cannot load http://localhost:54690/api/Storage/Get. The response to the preflight request does not pass the access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3333' is therefore denied access. The response returned a HTTP status code of 500.
Despite trying to add CORS, it seems like I might be doing it incorrectly. I attempted both server-side and client-side approaches.
var instance = axios.create({
baseURL: 'http://localhost:54690/api',
timeout: 1000,
headers: { 'Access-Control-Allow-Origin': '*' }
});
instance.get('/Storage/Get')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
For server-side implementation:
[EnableCors(origins: "http://localhost:3333/", headers: "*", methods: "*")]
public class StorageController : ApiController
WebapiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new EnableQueryAttribute());
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnableCors();
}
}
Edit:
It appears that by using [EnableCors(origins: "", headers: "", methods: "*")], it works without specifying anything in the header for AJAX. However, this may not be a suitable solution for production, right?
Is there a way to globally configure CORS? It's inconvenient to have to set it up for every controller.
Edit 2:
Further investigation based on the input from @kormali_2 suggests that the issue could be due to having "" instead of "". There might also be a global option available for CORS configuration.