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

前端 未结 11 609
隐瞒了意图╮
隐瞒了意图╮ 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:25

    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  
    
    0 讨论(0)
  • 2020-12-02 17:26

    in my case it was localhost:8000 while 127.0.0.1 was expected... changing localhost to 127.0.0.1 in my browser did the trick

    0 讨论(0)
  • 2020-12-02 17:29

    If using django for backend, you need to do the following 6 things:

    • ensure you are in the virtualenv, then 'pip install django-cors-headers'

    • add the following in your INSTALLED-APPS section of the settings.py: 'corsheaders',

    • add the following in the MIDDLEWARE section of the settings.py: 'corsheaders.middleware.CorsMiddleware',
      'django.middleware.common.CommonMiddleware',

    • add either of the following at the bottom of the settings.py:
      CORS_ORIGIN_ALLOW_ALL = True or

      CORS_ORIGIN_WHITELIST = [
      'http://localhost:3000',
      'http://127.0.0.1:3000'
      ]
      
    • When using CORS_ORIGIN_WHITELIST, use the URL of the front end app where the GET Or POST request is coming from.

    • Another gotcha is ensuring the URL pointing to django ends with a trailing slash.

    0 讨论(0)
  • 2020-12-02 17:31

    I have observed this error in 3 scenarios:

    1. When the URL didn't end with /.
    2. When URL had slashes like // or ///.
    3. When my server was not working. But after switching it on it worked fine.
    0 讨论(0)
  • 2020-12-02 17:35

    Add following line in middleware classes

    'corsheaders.middleware.CorsPostCsrfMiddleware'
    

    so overall implementation would be:

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

    check documentaion below for more info

    0 讨论(0)
提交回复
热议问题