Home > Software design >  django cors headers not working (yes ik a 100th people asked before but their solutions didn't
django cors headers not working (yes ik a 100th people asked before but their solutions didn't

Time:07-31

my settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'channels',
    'chatterapi',
    'chatterchannels',
    "corsheaders",
]

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ALLOW_ALL_ORIGINS: True

*the chatter apps are my apps, and i'm also using django channels. tried moving cors headers up and down but had no luck.

idk how to get the actual headers but here is the log :

enter image description here

my views.py ?

@api_view(['POST'])
def createRoom(request):
    key = get_random_string(15)
    request.POST._mutable = True
    request.data['key'] = key
    request.POST._mutable = False
    print(request.data)
    serializer = RoomSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    else:
        return Response(serializer.errors, status=400)

I really don't know what's going on, let me know if there is any way I can help. Is it possible that django channels overriding the runserver command is causing a conflict or something? (if that sounds dumb, please forgive me, cause I AM dumb)

CodePudding user response:

You use the wrong syntax for setting a variable value. Change the line

CORS_ALLOW_ALL_ORIGINS: True

to

CORS_ALLOW_ALL_ORIGINS = True

CodePudding user response:

Sometimes the below code may not work

CORS_ALLOW_ALL_ORIGINS = True

Try mentioning the hosts manually like below

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

]
  • Related