chobo2 chobo2 - 3 months ago 36
Ajax Question

How to enable CORS? Sever? Javascript? where?

right now I am testing my reactjs site on locahost:3333 and my asp.net web api 2 on localhost:54690.

I am using axios for my ajax but when I make a request I get an error.


XMLHttpRequest cannot load http://localhost:54690/api/Storage/Get.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3333' is therefore not allowed
access. The response had HTTP status code 500.


I tried to add Cors but guess I am not doing it right. I tried server side and client side.

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);
});


server side

[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

Seems like when I do this

[EnableCors(origins: "", headers: "", methods: "*")]

it works. I dont' even need to put anything in my header for my ajax. Though this not really a soultion as I don't want this to happen in production I am guessing?

Also is there a global function I can setup cors at? Kinda sucks to put it on every controller.

Edit 2

looking more into the link from @kormali_2 I see that the problem might be because I have "http://locahost:3333/" where it should be "http://locahost:3333" also there is a global option I can use.

Answer

You can enable CORS globally with this:

// Enable CORS globally for any host
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);

To enable it just for a specific host you would use:

// Enable CORS globally for specific host
var corsAttr = new EnableCorsAttribute("http://localhost:3333", "*", "*");
config.EnableCors(corsAttr);

More information at http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

Comments