0

Cross Origin Request Blocked

I have installed pip install django-cors-headers still not working

added into the settings.py file

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

enter image description here

enter image description here

Django Rest Framework

Abi Chhetri
  • 1,131
  • 10
  • 15

2 Answers2

2

I also had same issue in project solution that i got is

  1. Place corsheaders.middleware.CorsMiddleware at the top

    MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    ..........
    ..........
    ]
    
  2. ALLOWED_HOSTS = ['*']

  3. Add at the bottom of the settings.py

     CORS_ORIGIN_ALLOW_ALL = True
    

According to Documentation CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django’s CommonMiddleware or Whitenoise’s WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.

Also if you are using CORS_REPLACE_HTTPS_REFERER it should be placed before Django’s CsrfViewMiddleware (see more below).

Abi Chhetri
  • 1,131
  • 10
  • 15
1

Usually, for such error you need to update settings.py with django-cors-headers:

# update backend/server/server/settings.py
# ...
INSTALLED_APPS = [
    #...
    'corsheaders', # add it here
    #...
]

# define which origins are allowed
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000"
]

# add to middleware
MIDDLEWARE = [
    #...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    #...
]

Sometimes you also need to set ALLOWED_HOSTS=["127.0.0.1"] or with your other address (you can also try with "*", but just for debug).

You can check details in my article: React Token Based Authentication to Django REST API Backend.

Please also try to run tests with a cleared cache in the web browser.

If that doesn't help please provide more details about your project setup.

pplonski
  • 5,023
  • 1
  • 30
  • 34
  • please check my source source its not working https://github.com/avichhetri8/djangowithreact/blob/dev/ecom/settings.py – Abi Chhetri Dec 24 '20 at 10:49