chobo2 chobo2 - 2 months ago 21
Ajax Question

How to enable CORS? Sever? Javascript? where?

right now I am testing my reactjs site on locahost:3333 and my 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': '*' }

.then(function (response) {
.catch(function (error) {

server side

[EnableCors(origins: "http://localhost:3333/", headers: "*", methods: "*")]
public class StorageController : ApiController


public static class WebApiConfig
public static void Register(HttpConfiguration config)
config.Filters.Add(new EnableQueryAttribute());

// Web API configuration and services

// Web API routes

name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }



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.


You can enable CORS globally with this:

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

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

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

More information at