Enabling CORS in Angular JS

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', [
    'myAppApiService']);

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.

14 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)

Google I/O 2012 - Sessions I am looking forward to

Google I/O is probably the best Developer conference each year when it comes to new technologies in the web. Since I am in China, I am most likely not able to see the live streams of the conference, but will definitely check out the recordings afterwards.

Apart for the keynote the following are a must to check out for me:

Backend

Frontend

Google TV

Misc

Hope I have enough time to enjoy these.

0 Comment(s)