Monday 4 May 2015

CORS in Django REST Framework

Django REST Framework doesn't allow cross browser requests via AJAX. When we build a REST API it is usually exposed on a separate server and the applications using it have their own servers on which they run. Hence when we hit any of the REST URL via AJAX we get No 'Access-Control-Allow-Origin' header is present on the requested resource error. For instance,
Ext.Ajax.request({    
 url: 'http://localhost:8080/portal/categories',    
 method: 'GET',
 success: function(response){console.log(response)},
 failure: function(){console.log('failure');}
});

the above request, will result into following error.

XMLHttpRequest cannot load http://localhost:8080/portal/categories?_dc=1430698970456. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

This is because of no provision in the REST API to handle Cross-Origin-Resource-Request (CORS). To enable it in the REST API, we need django-cors-headers as recommended in Django REST Framework documentation. The minimal settings required are as follows.

Step 0 - install django-cors-headers,
>>> pip install django-cors-headers

Step 1 - In settings.py, add the following entry in INSTALLED_APPS tuple.
INSTALLED_APPS = (
 ...
 ...

 'corsheaders'
)

Step 2 - In settings.py, add the following entries at the top of MIDDLEWARE_CLASSES tuple.
MIDDLEWARE_CLASSES = (
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 
 ...
 ...
) 

Step 3 - Add the following flag variable in settings.py
CORS_ORIGIN_ALLOW_ALL = True 

We are done !!

Now you can again make the AJAX request as given in the beginning of this post & you will get the response in success handler as follows.
{
 requestId: 7
 responseText: "[{"name":"Database","href":"/portal/categories/1/scripts"},{"name":"RFB","href":"/portal/categories/2/scripts"},{"name":"Info Miner","href":"/portal/categories/3/scripts"}]"
 responseXML: null
 status: 200
 statusText: "OK"
 
 ...
 ...
}

For more configuration options visit django-cors-headers.

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.

Do you like this article?