Thursday, July 25, 2013

Cross Origin $http with Angular JS



Recently had the need to perform a cross domain ajax request in my Angular JS app. 

The naive approach (i.e - just perform the request and hope everything works) will result in an error similar to this:

Failed to load resource: Origin ... is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load ... Origin is not allowed by Access-Control-Allow-Origin.


"OPTIONS xxx Origin xxx is not allowed by Access-Control-Allow-Origin. angular.js:9312

XMLHttpRequest cannot load xxx. Origin xxx is not allowed by Access-Control-Allow-Origin. "

Now what you want is to have your server code to include a response header that tells the browser that this is actually OK:



If you're using Python, do something like this:
class Handler(webapp.RequestHandler):
    def get(self):
        img_data = get_status_image_for_current_user()
        self.response.headers["Access-Control-Allow-Origin"] = "*"

If your'e on ASP.NET, it would be feasible to do something like this:


code:
public class webtu : IHttpHandler {    
    public void ProcessRequest (HttpContext context) {
        context.Response.AddHeader("Access-Control-Allow-Origin", "*");    
...
...

(you might want to replace that * with your specific origin for better security)

On Angular, to make this possible, you would need to remove the default header being sent out to prevent this:

code:

angular.module('myModule')
    .config(function ( $httpProvider) {        
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }).factory('featuresData', function ($http) {
        return{          
            doCrossDomainGet: function() {
                return $http({
                    url:'http://other.domain.com',
                    method: 'GET'
                })
            }        
        }
});

And viola, cross origin is ajax is possible. 

No comments:

Post a Comment