Python django-cors-headers 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28046422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:40:07  来源:igfitidea点击:

django-cors-headers not work

pythondjangodjango-cors-headers

提问by Aby-Chan

django-cors-headers not work

django-cors-headers 不起作用

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.clickHymaning.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

回答by danius

According to the process_response code from CorsMiddleware:

根据CorsMiddleware的 process_response 代码:

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

回答by A. Rista

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

我猜 corsheaders 和点击劫持中间件不兼容。至少当我注释掉时,我摆脱了 X-Frame-Options 标题 django.middleware.clickHymaning.XFrameOptionsMiddleware

I've just CORS_ORIGIN_ALLOW_ALL = Truesetting.

我刚CORS_ORIGIN_ALLOW_ALL = True设置。

回答by mixja

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

如果您正在测试这个,您需要确保在请求中至少包含 Origin 标头。

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:

您将通过预检 CORS 请求获得更多反馈:

$ 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

回答by GreGGus

Do not forget to add

不要忘记添加

'corsheaders.middleware.CorsMiddleware',

'corsheaders.middleware.CorsMiddleware',

at top of MIDDLEWARE variable :

在 MIDDLEWARE 变量的顶部:

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.

CorsMiddleware 应该放在尽可能高的位置,尤其是在任何可以生成响应的中间件之前,例如 Django 的 CommonMiddleware 或 Whitenoise 的 WhiteNoiseMiddleware。如果之前没有,它将无法将 CORS 标头添加到这些响应中。

回答by Euron Metaliaj

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.

从 Django 2 MIDDLEWARE_CLASSES 改为 MIDDLEWARE。在这种情况下,如果您有 Django 2,请确保 MIDDLWARE 应该是这样的,以便 MIDDLEWARES 被执行。

回答by bitigital

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.

我遇到了同样的问题,一切似乎都在正确的地方。然后我发现我在添加'corsheaders.middleware.CorsMiddleware',MIDDLEWARE_CLASSES. 修正后,还是不行。尝试了一堆东西后,我在另一个浏览器中打开它,它工作正常。所以结果我只需要清除浏览器缓存。

回答by Googlian

Final solution would be send response with CORS allowed headers.

最终的解决方案是发送带有 CORS 允许标头的响应。

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"

回答by bhaskarc

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

尽管遵循了所有步骤django-cors-headersDjango 2但不知何故对我不起作用。飞行前检查将重新运行 405 错误。

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:

然后在我的中添加了这个中间件settings.py

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

This did the trick for me.

这对我有用。

回答by Nitish Chauhan

django-cors-headersworks perfectly for handling CORS policy issue.

django-cors-headers非常适合处理 CORS 政策问题。

After doing the above steps, just try to clear browser cache or try making same request in chrome(incognito) or firefox(private window).

完成上述步骤后,只需尝试清除浏览器缓存或尝试在 chrome(incognito) 或 firefox(private window) 中发出相同的请求。

回答by Cesar Gamboa Avellan

This worked for me:

这对我有用:

python -m pip install django-cors-headers
MIDDLEWARE = [  
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

`ALLOWED_HOSTS = ['*']`

`CORS_ORIGIN_ALLOW_ALL = True`

Make sure to include: corsheaders.middleware.CorsMiddleware, as high as possible

确保包括:corsheaders.middleware.CorsMiddleware, 尽可能高

For reference: https://pypi.org/project/django-cors-headers/, https://docs.djangoproject.com/en/3.0/ref/settings/

供参考:https: //pypi.org/project/django-cors-headers/,https: //docs.djangoproject.com/en/3.0/ref/settings/