I'm trying to setup AngularJS to communicate with a cross-origin resource where the asset host which delivers my template files is on a different domain and therefore the XHR request that angular performs must be cross-domain. I've added the appropriate CORS header to my server for the HTTP request to make this work, but it doesn't seem to work. The problem is that when I inspect the HTTP requests in my browser (chrome) the request sent to the asset file is an OPTIONS request (it should be a GET request).
I'm not sure whether this is a bug in AngularJS or if I need to configure something. From what I understand the XHR wrapper can't make an OPTIONS HTTP request so it looks like the browser is trying to figure out if is "allowed" to download the asset first before it performs the GET request. If this is the case, then do I need to set the CORS header (Access-Control-Allow-Origin: http://asset.host...) with the asset host as well?
For Angular 1.2.0rc1+ you need to add a resourceUrlWhitelist.
1.2: release version they added a escapeForRegexp function so you no longer have to escape the strings. You can just add the url directly
make sure to add ** for sub folders. Here is a working jsbin for 1.2: http://jsbin.com/olavok/145/edit
1.2.0rc: If you are still on a rc version, the Angular 1.2.0rc1 the solution looks like:
Here is a jsbin example where it works for 1.2.0rc1: http://jsbin.com/olavok/144/edit
Pre 1.2: For older versions (ref http://better-inter.net/enabling-cors-in-angular-js/) you need to add the following 2 lines to your config:
Here is a jsbin example where it works for pre 1.2 versions: http://jsbin.com/olavok/11/edit
NOTE: Not sure it works with the latest version of Angular.
ORIGINAL:
It's also possible to override the OPTIONS request (was only tested in Chrome):
Here is the way I fixed this issue on ASP.NET
First, you should add the nuget package Microsoft.AspNet.WebApi.Cors
Then modify the file App_Start\WebApiConfig.cs
Add this attribute on your controller class
I was able to send json to the action by this way
Reference : Enabling Cross-Origin Requests in ASP.NET Web API 2
Your service must answer an
OPTIONS
request with headers like these:Here is a good doc: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server
For an IIS MVC 5 / Angular CLI ( Yes, I am well aware your problem is with Angular JS ) project with API I did the following:
web.config under
<system.webServer>
nodeglobal.asax.cs
That should fix your issues for both MVC and WebAPI without having to do all the other run around. I then created an HttpInterceptor in the Angular CLI project that automatically added in the the relevant header information. Hope this helps someone out in a similar situation.
If you are using a nodeJS server, you can use this library, it worked fine for me https://github.com/expressjs/cors
and after you can do an
npm update
.