Django cors 标头不适用于 django 通道

问题描述 投票:0回答:1

我在 django 中有一个项目,当我添加 django 通道时,我的 cors 停止正常工作

# settings.py

...
...
...

DEBUG = True

ALLOWED_HOSTS = ['localhost']

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
]

CSRF_TRUSTED_ORIGINS =[  
    "http://localhost:3000",
]

CORS_ALLOW_CREDENTIALS = True

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

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    ...
]

...
...
...
...

WSGI_APPLICATION = 'config.wsgi.application'
ASGI_APPLICATION = 'config.asgi.application'


# asgi.py

from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from django.core.asgi import get_asgi_application

websocket_urlpatterns = [
  
]

application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': URLRouter(
        websocket_urlpatterns
    ),
})

浏览器中的错误是:

Access to XMLHttpRequest at 'http://localhost:8000/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当我从设置文件中删除 ASGI_APPLICATION 并从应用程序列表中删除频道时,cors 就可以工作了。

为什么?

这是我的版本:

channels==3.0.4
Django==4.0.0
django-cors-headers==4.0.0

我尝试将自己的中间件添加到列表顶部

def open_access_middleware(get_response):
    def middleware(request):
        response = get_response(request)
        print('Test')
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Headers"] = "*"
        return response
    return middleware

但还是不行。

python django cors django-channels django-cors-headers
1个回答
0
投票

您的

settings.py
缺少
Access-Control-Allow-Origin
的配置。

您可以使用以下代码添加它:

CORS_ALLOW_ALL_ORIGINS = True

您可能还需要此设置:

CORS_ORIGIN_ALLOW_ALL = True
© www.soinside.com 2019 - 2024. All rights reserved.