Django + React Axios 网络错误:Access-Control-Allow-Credentials 预期为“true”

问题描述 投票:0回答:1

我正在开发一个在前端运行 React 并在后端运行 Django 的 Web 应用程序,并且在向后端发送 api 请求时遇到了问题。尝试 POST 或 GET 请求时,网站上会弹出 Axios 网络错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/is_authenticated/. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’).

尽管如此,在 Firefox 中检查网络请求时,JSON 响应确实包含正确的数据,并且状态为 200 OK。仅出现一条警告“脚本无法使用响应正文(原因:CORS 缺少允许凭据)”。

我当前使用 CorsMiddleware 的后端设置是

INSTALLED_APPS = [
    ...
    'app',
    'corsheaders',
    'rest_framework',
    ...
]
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]
CORS_ALLOW_CREDENTIALS: True
CSRF_COOKIE_SECURE = False, 
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:3000',
    'http://127.0.0.1:8000',
    'http://localhost:3000',
    'http://localhost:8000',
]

发送请求时,我有当前的 axios post 调用。

axios.post(`http://localhost:8000/login/`, request, { withCredentials: true })
    .then(({ data }) => {
      if (data.warning) return;
        localStorage.setItem("currentUser", data.user);
    });

我的代码中是否存在我忽略的设置或特定错误?或者 Axios 上是否有某些前端设置需要更新以允许凭据?谢谢您的帮助。

reactjs django axios django-cors-headers
1个回答
0
投票

哎呀,这很尴尬,但是在撞了大约 4 个小时的头之后。意识到我做了

Cors-Allow-Credentials: True
而不是
Cors-Allow-Credentials = True

© www.soinside.com 2019 - 2024. All rights reserved.