如何在 Django 中启用 cors (DJANGO + REACT)

How to enable cors in django (DJANDO + REACT)

Access to XMLHttpRequest at 'http://127.0.0.1:8000/lessons/student' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

xhr.js:177 GET http://127.0.0.1:8000/lessons/student net::ERR_FAILED

在我的本地主机上运行良好,我从 API 获取数据,但是当我的朋友尝试转到“课程”页面并获取数据时,它显示该错误;

在后端,我下载了 django-cors 或任何它被调用的东西,并按照所述做了所有事情

CORS_ORIGIN_ALLOW_ALL = True

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'corsheaders',

    'News',
    'Users',
    'Lessons',
    'Tests',
    'GradeBook',
    'Schedule',
    'DeadLines'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',

]

我使用带有 axios 的 redux-thunk 获取数据

 const lesson = await axios.get(`${url}/lessons/student`, {
        headers: {
          "Authorization": "JWT " + getState().auth.token.access,
        }
      })

我已经检查了很多类似问题的答案,但他们只说我应该安装 django-cors..enable cors...lalal...我做了一切重新加载服务器甚至本地主机,但它仍然没有'没用。

也不是浏览器的问题,我朋友试过chrome因为他用的是opera。 又一次,在我的电脑上它运行良好。我访问该网页后便获得了数据,如果我在另一台计算机上尝试它会显示错误。我该如何解决这些问题?

尝试在所有中间件之前添加 corsheaders.middleware.CorsMiddleware(即)MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', ...]

参考:https://pypi.org/project/django-cors-headers/