Search code examples
pythondjangodjango-rest-frameworkdjango-cors-headers

CORS header missing when project hosted in a Subpath


I have a Django(v2.2) project hosted on an url which looks like https://some.example.com/mypath/ which has an API endpoint at blog/create. I need to make a POST request from https://some.example.com/anotherpath/ofmine/ (using axios), but that gives me a 301 error with the following messages in Firefox 71.0:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some.example.com/mypath/blog/create/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some.example.com/mypath/blog/create/. (Reason: CORS request did not succeed).

However, I can easily make the same requests to a dev server hosted locally.

Relevant settings:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'rest_framework_docs',
    'corsheaders',                                                          
    'django_extensions',
    ...
]

USE_X_FORWARDED_HOST = True
FORCE_SCRIPT_NAME = '/mypath'
CORS_ORIGIN_ALLOW_ALL = True

What could be the reason and possible workarounds for the error?


Solution

  • Stupid mistake. some.example.com redirects to www.some.example.com so I'd been trying to access APIs at some.example.com (which doesn't exist, hence the 301) from www.some.example.com. Prefixed the www on the request url and it's working fine; I don't even need CORS headers, of course.