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

匿名 (未验证) 提交于 2019-12-03 01:57:01

问题:

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.

回答1:

Your front and back end are on different ports which means your ajax requests are subject to cross origin security.

You need to set up the back end to accept requests from different origins (or just different port numbers).

Try reading up on CORS and more specifically looking at django cors headers



回答2:

Here's what i did when i got the same error form Django rest framework while sending API request from Restangular. What it does is that it adds CORS (Cross-Origin Resource Sharing) headers to responses from Django Rest Framework, which if not was the cause of the error.

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

pip install django-cors-headers

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

After installing it , you have to make some edit 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



回答3:

In my case, I had simply forgotten to add a trailing slash at the end of the REST API URL. ie, I had this:

http://127.0.0.1:8000/rest-auth/login

Instead of this:

http://127.0.0.1:8000/rest-auth/login/


回答4:

If django-cors-headers not resolved the problem try manual add Access-Control-Allow-Origin like this:

@api_view(['GET']) def swanger(request):   resutl = {'a': 1}   resp = JsonResponse(resutl)   resp['Access-Control-Allow-Origin'] = '*'   return resp  


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!