Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cors Error #60

Open
ikrma47 opened this issue Jun 28, 2022 · 3 comments
Open

Cors Error #60

ikrma47 opened this issue Jun 28, 2022 · 3 comments

Comments

@ikrma47
Copy link

ikrma47 commented Jun 28, 2022

Hello,

I've been stuck at cors issue with reconnecting event source.
All my others API's are working fine but when I use ReconnectingEventSource I start facing Cors error.

my code at frontend with react

function App() {

  useEffect(() => {


    let es = new ReconnectingEventSource("http://localhost:8000/events/")
    es.onopen = function (){
      console.log("connected")
    }
  },[])
}

backend code

settings.py

CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = ["localhost"]

CORS_ALLOWED_ORIGINS = ["http://localhost"]
CORS_ALLOW_CREDENTIALS = False


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

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

asgi.py

import os

from django.core.asgi import get_asgi_application
from django.conf.urls import url
from channels.routing import ProtocolTypeRouter, URLRouter
# from channels.auth import AuthMiddlewareStack
import django_eventstream

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

application = ProtocolTypeRouter({
    'http': URLRouter([
        url(r'^events/', 
            URLRouter(django_eventstream.routing.urlpatterns)
        , { 'channels': ['test'] }),
        url(r'', get_asgi_application()),
    ]),
})

image

image

if work with templates in django, it works very well without any error. but I want to use react at my frontend side. please let me know how to fix this error. I'm stuck at it very badly.

@nirmal-chg
Copy link

In your frontend can you try this and see if it works.

function App() {

  useEffect(() => {


    let es = new ReconnectingEventSource("http://localhost:8000/events/", { withCredentials: true })
    es.onopen = function (){
      console.log("connected")
    }
  },[])
}

@ikrma47
Copy link
Author

ikrma47 commented Jul 31, 2022

It's still the same error. :((

@jkarneges
Copy link
Member

Unfortunately, regular middlewares don't work with Django Channels.

In the meantime, try these settings:
https://github.com/fanout/django-eventstream#cross-origin-resource-sharing-cors-headers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants