Not allowed by Access-Control-Allow-Origin

Please note that “Access-Control-Allow” error in Chrome console can mask the real error.  It is best to use Fiddler2 to examine the request and response.  In one occasion, it was actually caused by an Entity Framework error due to outdated model.

When one browse a local html file with jquery $.getJSON(url, …), one may get the following error:

XMLHttpRequest cannot load http://xxxx.xxx/xxx/xxxx. Origin null is not allowed by Access-Control-Allow-Origin.

Even if you set up a local web server to serve the same html page with $.getJSON(), you can get a similar error.  The cause is Same Origin Policy.  You can google it.

There are many workarounds, including:

  1. Use JSONP
  2. When running google chrome browser, add “–disable-web-security” as an argument.  Obviously, you want to do it only in a safe development environment.

For MVC Web Api, one can add the following code to a controller method:

System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
 
 
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s