简体   繁体   English

跨域请求被阻止 Django 和反应

[英]Cross-Origin Request Blocked Django and React

跨域请求被阻止

I have installed pip install django-cors-headers still not working我已经安装了pip install django-cors-headers仍然无法正常工作

added into the settings.py file添加到 settings.py 文件中

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

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

在此处输入图像描述

在此处输入图像描述

Django Rest Framework Django Rest 框架

Usually, for such error you need to update settings.py with django-cors-headers :通常,对于此类错误,您需要使用django-cors-headers更新settings.py

# 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).有时您还需要设置ALLOWED_HOSTS=["127.0.0.1"]或您的其他地址(您也可以尝试使用“*”,但仅用于调试)。

You can check details in my article: React Token Based Authentication to Django REST API Backend .您可以在我的文章中查看详细信息: React Token Based Authentication to Django REST API 后端

Please also try to run tests with a cleared cache in the web browser.还请尝试在 web 浏览器中运行清除缓存的测试。

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将 corsheaders.middleware.CorsMiddleware 放在顶部

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

  3. Add at the bottom of the settings.py在 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.根据文档CorsMiddleware 应放置在尽可能高的位置,尤其是在任何可以生成响应的中间件之前,例如 Django 的 CommonMiddleware 或 Whitenoise 的 WhiteNoiseMiddleware。 If it is not before, it will not be able to add the CORS headers to these responses.如果不是之前,它将无法将 CORS 标头添加到这些响应中。

Also if you are using CORS_REPLACE_HTTPS_REFERER it should be placed before Django's CsrfViewMiddleware (see more below).此外,如果您使用的是 CORS_REPLACE_HTTPS_REFERER,它应该放在 Django 的 CsrfViewMiddleware 之前(见下文)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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