django-cors-headers not work

后端 未结 13 1438
情深已故
情深已故 2020-12-29 04:10

django-cors-headers not work

INSTALLED_APPS = (
    \'django.contrib.admin\',
    \'django.contrib.auth\',
    \'django.contrib.contenttypes\',
    \'django.         


        
13条回答
  •  盖世英雄少女心
    2020-12-29 04:18

    Somehow django-cors-headers would not work for me with Django 2 despite following all the steps. The pre-flight check would retrun a 405 error.

    I ended up writing a small middleware:

    from django import http
    
    
    class CorsMiddleware(object):
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            response = self.get_response(request)
            if (request.method == "OPTIONS"  and "HTTP_ACCESS_CONTROL_REQUEST_METHOD" in request.META):
                response = http.HttpResponse()
                response["Content-Length"] = "0"
                response["Access-Control-Max-Age"] = 86400
            response["Access-Control-Allow-Origin"] = "*"
            response["Access-Control-Allow-Methods"] = "DELETE, GET, OPTIONS, PATCH, POST, PUT"
            response["Access-Control-Allow-Headers"] = "accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with"
            return response
    

    Then added this middleware in my settings.py :

    MIDDLEWARE = [
        'apps.core.middleware.CorsMiddleware',
         ... others below it
    ]
    

    This did the trick for me.

提交回复
热议问题