简体   繁体   中英

Cross-Origin Request Blocked Django and React

跨域请求被阻止

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',
    ...
]

在此处输入图像描述

在此处输入图像描述

Django Rest Framework

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM