跨域请求阻止 Django 和 React

时间:2020-12-23 08:33:58

标签: javascript python reactjs django django-rest-framework

Cross Origin Request Blocked

我已经安装了 pip install django-cors-headers 仍然无法工作

添加到settings.py文件中

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

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

enter image description here

enter image description here

Django Rest 框架

2 个答案:

答案 0 :(得分:0)

通常,对于此类错误,您需要将 settings.py 更新为 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',
    #...
]

有时您还需要设置 ALLOWED_HOSTS=["127.0.0.1"] 或您的其他地址(您也可以尝试使用“*”,但只是为了调试)。

您可以在我的文章中查看详细信息:React Token Based Authentication to Django REST API Backend

还请尝试在网络浏览器中清除缓存的情况下运行测试。

如果这没有帮助,请提供有关您的项目设置的更多详细信息。

答案 1 :(得分:0)

我在项目解决方案中也遇到了同样的问题

  1. 将 corsheaders.middleware.CorsMiddleware 放在顶部

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

  3. 在settings.py底部添加

     CORS_ORIGIN_ALLOW_ALL = True
    

根据Documentation CorsMiddleware 应该放在尽可能高的位置,尤其是在任何可以生成响应的中间件之前,例如 Django 的 CommonMiddleware 或 Whitenoise 的 WhiteNoiseMiddleware。如果之前没有,它将无法将 CORS 标头添加到这些响应中。

另外,如果你使用 CORS_REPLACE_HTTPS_REFERER,它应该放在 Django 的 CsrfViewMiddleware 之前(见下文)。