I have a project in django and when I added django channels my cors stopped working correctly
# 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'
# routing
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
),
})
Error in browser is:
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.
And when I remove ASGI_APPLICATION from settings file and channels from APPS list then cors works.
Whyy?
This is my versions:
channels==3.0.4
Django==4.0.0
django-cors-headers==4.0.0
I tried to add my own middleware to the top of the list
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
but it still not working.
New contributor