django-cors-headers not work

大城市里の小女人 提交于 2019-12-18 11:45:44

问题


django-cors-headers not work

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'corsheaders',
    'rest_framework',
    'world',
    'userManager',
    'markPost',
    'BasicServices',
)


MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

Everything is normal, but did not work

here my response headers

Cache-Control: max-age=0
Content-Type: text/html; charset=utf-8
Date: Tue, 20 Jan 2015 13:16:17 GMT
Expires: Tue, 20 Jan 2015 13:16:17 GMT
Last-Modified: Tue, 20 Jan 2015 13:16:17 GMT
Server: WSGIServer/0.1 Python/2.7.8
Set-Cookie: csrftoken=snXksqpljbCLW0eZ0EElFxKbiUkYIvK0; expires=Tue, 19-Jan-2016 13:16:17 GMT; Max-Age=31449600; Path=/
Vary: Cookie
X-Frame-Options: SAMEORIGIN

回答1:


According to the process_response code from CorsMiddleware:

response[ACCESS_CONTROL_ALLOW_ORIGIN] = "*" if (
            settings.CORS_ORIGIN_ALLOW_ALL and
            not settings.CORS_ALLOW_CREDENTIALS) else origin

You must set settings like this:

# CORS Config
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False



回答2:


If you are testing this you need to ensure you include at least the Origin header in the request.

E.g.:

$ http GET http://127.0.0.1:8000/todos/ Origin:http://www.someorigin.com
HTTP/1.0 200 OK
Access-Control-Allow-Origin: *
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Date: Sat, 14 Nov 2015 04:42:38 GMT
Server: WSGIServer/0.1 Python/2.7.10
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

You will get more feedback with a preflight CORS request:

$ http OPTIONS http://127.0.0.1:8000/todos/ Origin:http://www.someorigin.com
HTTP/1.0 200 OK
Access-Control-Allow-Headers: x-requested-with, content-type, accept, origin, authorization, x-csrftoken, user-agent, accept-encoding
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 86400
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Date: Sat, 14 Nov 2015 04:45:37 GMT
Server: WSGIServer/0.1 Python/2.7.10
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN



回答3:


I guess corsheaders and clickjacking middlewares are not compatible. At least I got rid off X-Frame-Options header when I commented out django.middleware.clickjacking.XFrameOptionsMiddleware.

I've just CORS_ORIGIN_ALLOW_ALL = True setting.




回答4:


I was having this same issue and everything seemed to be in the right place. Then I figured out that I had started the server before adding 'corsheaders.middleware.CorsMiddleware', to the MIDDLEWARE_CLASSES. After making the correction, it was still not working. After trying a bunch of stuff, I opened it in another browser and it worked. So it turned out that I just needed to clear the browser cache.




回答5:


From Django 2 MIDDLEWARE_CLASSES is changed to MIDDLEWARE. In this case if you have Django 2 make sure the MIDDLWARE is as it should be such that MIDDLEWARES get executed.




回答6:


Do not forget to add

'corsheaders.middleware.CorsMiddleware',

at top of MIDDLEWARE variable :

See docs :

CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware or Whitenoise's WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.




回答7:


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.




回答8:


Final solution would be send response with CORS allowed headers.

response["Access-Control-Allow-Origin"] = "*"
response['Content-Type'] = "application/json; charset=utf-8"
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type, My-Token"


来源:https://stackoverflow.com/questions/28046422/django-cors-headers-not-work

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