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

前端 未结 11 685
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 16:44

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 XM         


        
11条回答
  •  攒了一身酷
    2020-12-02 17:18

    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

提交回复
热议问题