Jeroj82 Jeroj82 - 5 months ago 43
jQuery Question

No 'Access-Control-Allow-Origin' on the localhost

I have backend in Django and REST framework for API serving.
I'm trying to make nativ app with cordova framework.

I built some service:

var RegionService = function(){
var url;

this.initialize = function(){
url = "http://127.0.0.1:8000/api/regions/";
var deferred = $.Deferred();
deferred.resolve();
return deferred.promise();
}

this.List = function(){
return $.ajax({
type : "GET",
url : url
});
}

this.Get = function(id){
return $.ajax({
type : "GET",
url : url + id + "/"
});
}

}


and in index.js

var regions = new RegionService();

regions.initialize().done(function() {
console.log("Regions initialized");

regions.List().done(function(data){
console.log("LIST");
console.log(data);
});
});


I'm testing cordova by browser platform:
cordova run browser

And when I run this app I get in console in browser:

Regions initialized
XMLHttpRequest cannot load http://127.0.0.1:8000/api/regions/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8001' is therefore not allowed access.


Django backend run on 127.0.0.1:8000, and mobile app 127.0.0.1:8001

Answer

Sounds like you need to enable CORS (Cross Origin Resource Sharing) on your django backend. Check out this django app: https://github.com/ottoyiu/django-cors-headers/

The app adds middleware that adds CORS headers on every response, so you don't have to change any of your views, or the views from the django rest framework.

pip install django-cors-headers

In your settings.py:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
)

CORS_ORIGIN_WHITELIST = (
  '127.0.0.1:8001',
)

While developing locally, you could also try the setting: CORS_ORIGIN_ALLOW_ALL = True to allow cross-site requests from any host. You shouldn't do that in any non-local environment though.