Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"No 'Access-Control-Allow-Origin' header is present on the requested resource" in django

Tags:

django

I am newbie to django and using it as back end for an application that creates users. In front end the code for posting the user name is :

var xobj = new XMLHttpRequest();               xobj.overrideMimeType("application/json");               xobj.open('POST', "http://www.local:8000/create_user/", true);                 xobj.setRequestHeader("Access-Control-Allow-Origin", "*");               xobj.onreadystatechange = function () {                   if (xobj.readyState == 4 && xobj.status == "200") {                       console.log(xobj.responseText);                   }             }               xobj.send(json);     

On back end the function associated with url handles json but i am getting the error "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.local:54521' is therefore not allowed access". What is the solution for this problem? Also I have followed the steps from "https://gist.github.com/strogonoff/1369619", but problem persists.

like image 930
pnv Avatar asked Mar 18 '14 10:03

pnv


People also ask

How do I fix CORS header Access-Control allow Origin missing?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.

What are Django-CORS-headers?

django-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS).


1 Answers

Here's what I did when I got the same error from Django Rest Framework while sending an API request from Restangular. What this does is add CORS (Cross-Origin Resource Sharing) headers to responses from Django Rest Framework. Not having CORS headers was the cause of the error.

In the Django Project root folder (where the manage.py file is located), do:

pip install django-cors-headers 

I tried it using virtualenv but was not able to get it to work, so I installed it without switching to virtualenv and got it installed.

After installing it, you have to make some edits to your django settings.py

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

Setting above to true allows all origins to be accepted.

References: https://github.com/ottoyiu/django-cors-headers

like image 123
user3785412 Avatar answered Oct 13 '22 22:10

user3785412