Django CORS headers – You want to use ‘Cache-Control’

I was happily writing React app, and at one point, I realized I have to not have any cache at all to access Django API. So, I added,

headers: { "cache-control": "no-store" }

Then, Django API complains. I knew I already set up CORS middleware so I thought I am all set. For development, Django/React are being developed and need to do a bit of HTTP dance so I disabled the CORS check, I thought.
Long sotry short, as I read the code, what React app is complaining is that the “cache-control” is not part of approved headers.
Take a look at "site-packages/corsheaders/conf.py"

class Settings:
    """
    Shadow Django's settings with a little logic
    """

    @property
    def CORS_ALLOW_HEADERS(self):
        return getattr(settings, "CORS_ALLOW_HEADERS", default_headers)

    @property
    def CORS_ALLOW_METHODS(self):
        return getattr(settings, "CORS_ALLOW_METHODS", default_methods)

    @property
    def CORS_ALLOW_CREDENTIALS(self):
        return getattr(settings, "CORS_ALLOW_CREDENTIALS", False)

    @property
    def CORS_PREFLIGHT_MAX_AGE(self):
        return getattr(settings, "CORS_PREFLIGHT_MAX_AGE", 86400)

    @property
    def CORS_ORIGIN_ALLOW_ALL(self):
        return getattr(settings, "CORS_ORIGIN_ALLOW_ALL", False)
...

In my setting, I did "CORS_ORIGIN_ALLOW_ALL=true"so that part Okayes any origin, but to use cache-control header, you now have to set "CORS_ALLOW_HEADERS".
Since setting CORS_ALLOW_HEADERS in settings.py completely replaces the value, I copied the default header, and set it as follows:

CORS_ALLOW_HEADERS = [
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
    "cache-control",
    "credentials",
    "http-access-control-request-method",
]

# if you want to allow all. You could use whitelist instead.
CORS_ORIGIN_ALLOW_ALL = True

Now, my React app is back to accessing Django.

Leave a Reply

Your email address will not be published. Required fields are marked *