djangoangularcorsbackenddjango-cors-headers

CORS header on OPTIONS request?


I am trying to set up a webapp with Angular and Django but I have a problem with the CORS headers.

As far as I understand, in order to include cookie data from the frontend in the request (such as csrf token and session id), I need to set the withCredentials to true in the request. So a GET request looks like this.http.get(this.url, { withCredentials: true });. Then the browser says

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at xxx. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’).

I can fix this for the GET request by adding the header to the response with response["Access-Control-Allow-Credentials"] = "true", but the problem comes when I make a POST request. In this case the frontend automatically sends an OPTIONS request before the POST, which as far as I understand is standard and is used to check what the backend allows to be posted. However, I can't set the CORS header for the response of the OPTIONS request, so in effect I can't send a POST request.

Is there a way to set the header for OPTIONS responses or am I doing something wrong in general?


Solution

  • Yes, there is a way to set the header for OPTIONS responses.

    1. Install django-cors-headers (if not already installed) :

    You can do this by running:

    pip install django-cors-headers
    
    1. Configure django-cors-headers:

    Next, add corsheaders to your installed apps and middleware in your settings.py file:

    INSTALLED_APPS = [
        ...
        'corsheaders',
        ...
    ]
    
    MIDDLEWARE = [
        ...
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.common.CommonMiddleware',
        ...
    ]
    
    CORS_ORIGIN_ALLOW_ALL = True
    CORS_ALLOW_CREDENTIALS = True
    

    So if you’ll follow the described above steps, your Django backend will respond to the OPTIONS requests properly and set the proper CORS headers, so your angular application will be able to make the POST requests without getting the CORS problems.