DRF+Axios: some requests fail with `ERR_NETWORK` or `ERR_BLOCKED_BY_CLIENT`

This is not a question, more like an answer to this common problem.

I have a Dashboard built with NextJs and Django+DRF and i am using axios as a HTTP Client.

i have noticed that some of my requests go through, and some do not (mainly the requests that fetch for example monthly/yearly payments/expenses of the company).

Down below you'll find the solution to this problem.

Solutions that might fix this issue:

  • Setup CORS properly on your django server settings.py:
    # CSRF
    # Either Update Axios settings or Django Settings
    CSRF_COOKIE_NAME = 'XSRF-TOKEN'
    CSRF_HEADER_NAME = 'HTTP_X_XSRF_TOKEN'

    # CORS
    CORS_ALLOW_ALL_ORIGINS = True # Do not run your production server with this setting
    CORS_ALLOW_CREDENTIALS = True

    from corsheaders.defaults import default_headers
    CORS_ALLOW_HEADERS = list(default_headers) + [
        'x-xsrf-token',
        'access-control-allow-headers', # this one is important
    ]

    CSRF_TRUSTED_ORIGINS = [
        'http://localhost:8000',
        'http://localhost:3000'
    ]

    CORS_ORIGIN_WHITELIST = [
        'http://localhost:8000',
        'http://localhost:3000',
    ]
  • If your are running Ublock Origin or any browser extension of this sort, turn it off for 127.0.0.1 and localhost
  • For Brave browser, turn off the shield for 127.0.0.1 and localhost
  • That's it, hope it helps.

i solve similar problem in Django(not DRF), it reproduce when try to deploy django+gunicorn+nginx in compose.

But i use https://pypi.org/project/django-cors-headers/

#settings.py just add:

INSTALLED_APPS = [
    'corsheaders',

]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
]

CORS_ALLOWED_ORIGINS = [
#and add your site address with ports
    "http://127.0.0.1:8001",
    "http://localhost:8001",
]
Back to Top