"No 'Access-Control-Allow-Origin' header is present on the requested resource" in django

Here's what I did when I got the same error from Django Rest Framework while sending an API request from Restangular. What this does is add CORS (Cross-Origin Resource Sharing) headers to responses from Django Rest Framework. Not having CORS headers was the cause of the error.

In the Django Project root folder (where the manage.py file is located), do:

pip install django-cors-headers

I tried it using virtualenv but was not able to get it to work, so I installed it without switching to virtualenv and got it installed.

After installing it, you have to make some edits to your django settings.py

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

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
)

CORS_ORIGIN_ALLOW_ALL = True   

Setting above to true allows all origins to be accepted.

References: https://github.com/ottoyiu/django-cors-headers


In my case, I had simply forgotten to add a trailing slash at the end of the REST API URL. ie, I had this:

http://127.0.0.1:8000/rest-auth/login

Instead of this:

http://127.0.0.1:8000/rest-auth/login/

Your front and back end are on different ports which means your ajax requests are subject to cross origin security.

You need to set up the back end to accept requests from different origins (or just different port numbers).

Try reading up on CORS and more specifically looking at django cors headers

Tags:

Django