Cross Domain ajax OPTIONS error 403 (Django)

后端 未结 1 1941
一整个雨季
一整个雨季 2020-12-21 12:24

I\'m developing some site aaa.com with django, which sends cross-domain ajax \"GET\" requests to receive json data from bbb.com which is also running on django and is using

相关标签:
1条回答
  • 2020-12-21 13:12

    You have to CORS whitelist your client to access the server.

    In case their is a Cross-domain request, the request becomes preflighted if you use methods other than GET, HEAD or POST.

    Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, it becomes preflighted.

    Its the server that allows the cross-domain client request to be processed or deny it (default).

    So if you have access to the server-side application, you could do the following to get the response.

    On server-side

    Install django-cors-headers on your server side and white list your client domain or IP (it is also port specific)

    pip install django-cors-headers
    

    In settings.py, add it in your INSTALLED_APPS

    INSTALLED_APPS = (
    ...
        'corsheaders',
    ...
    )
    

    Add the corsheaders.middleware.CorsMiddleware in MIDDLEWARE_CLASSES

    MIDDLEWARE_CLASSES = (
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        '**corsheaders.middleware.CorsMiddleware**',
        'django.middleware.common.CommonMiddleware',
    ....
    )
    

    and define a CORS whitelist

    CORS_ORIGIN_WHITELIST = (
        'aaa.com',
    )
    

    Now as you have added your client in the CORS whitelist, you will now be able to make a successful ajax request.

    0 讨论(0)
提交回复
热议问题