Enabling CORS in Angular JS

Note: This post covers how to enable CORS with AngularJS<1.2. Apparently in the latest AngularJS versions you don't have to add anything to make it work.

I was recently experimenting with building an API with django-tastypie and make it accessible via CORS, so it can be used from a different host from an AngularJS app.

For the Django part it was relatively straightforward. I could have either written my own Middleware, dealing with incoming CORS requests, but decided to use django-cors-headers in the end. Following the instructions in the github repo and adding my host where AngularJS is hosted to the CORS_ORIGIN_WHITELIST setting did enable the Django server to handle CORS.

With AngularJS it was a little more tricky, mainly because information is spread all over the web. Beside the fact that I was trying to implement a service using ngResource to communicate with the API, the following did enable AngularJS to send its requests with the appropriate CORS headers globally for the whole app:

var myApp = angular.module('myApp', [

myApp.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];


Just setting useXDomain to true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.

180 Comment(s)

Learn something new: AngularJS

I recently discovered AnguarJS after a post about it on the Google Developers Blog.

After going through the tutorial and watching a couple screen casts I am quite impressed. You can literally build a functional web app in just a few lines of code. The data-binding feature is great. Say goodbye to custom cycles from your html to JavaScript and back to populate the data in your page.

Using AngularJS does not mean you have to get rid of JQuery and other tools you are used to develop with (especially because JQuery has so many great plugins). It integrates nicely with AngularJS.

The only thing which bugged me was that Angular is using the same curly braces for template variables/tags as Django does. Luckily there already is a solution for this.

I definitively plan to use Angular for upcoming projects.

0 Comment(s)