简体   繁体   中英

django cors headers not working (yes ik a 100th people asked before but their solutions didn't work)

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:

在此处输入图像描述

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)

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

CORS_ALLOW_ALL_ORIGINS: True

to

CORS_ALLOW_ALL_ORIGINS = True

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",

]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM