django-cors-headers 不允许来自允许来源的请求

3 python django django-cors-headers fetch-api next.js

我面临的问题是我无法从 NextJS 前端获取现有用户。我使用的后端框架是 Django(以及 django-cors-headers 包)。django-cors-headers 不允许某个 HTTP 请求,但它应该允许。

\n

我的 next.config.js 包含重写,以便我可以访问我的后端。

\n
async redirects() {\n    return [\n      {\n        source: \'/api/:path*\',\n        destination: \'http://localhost:8000/:path*/\',\n        permanent: true,\n      },\n    ]\n  },\n
Run Code Online (Sandbox Code Playgroud)\n

我的 django-cors-headers 设置如下所示:

\n
# CORS\n\nCSRF_TRUSTED_ORIGINS = [\n    \'http://localhost:3000\',\n]\n\nCORS_ALLOWED_ORIGINS = [\n    \'http://localhost:3000\',\n    \'http://localhost:8000\',\n    \'http://127.0.0.1:3000\',\n    \'http://127.0.0.1:8000\',\n]\n\nCORS_ALLOW_ALL_ORIGINS = True\n
Run Code Online (Sandbox Code Playgroud)\n

失败的请求尝试获取 ID 为 1 的用户。该用户存在,因此该请求应该成功。

\n
fetch(`/api/users/${String(userId)}/`, {\n    mode: \'cors\',\n    credentials: \'include\',\n    headers: {\n      \'Content-Type\': \'application/json\',\n    },\n  })\n
Run Code Online (Sandbox Code Playgroud)\n

但是,我从请求中得到的唯一结果是有关 CORS 的错误消息。

\n
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/users/1.\n(Reason: CORS header \xe2\x80\x98Access-Control-Allow-Origin\xe2\x80\x99 missing).\nStatus code: 301.\n
Run Code Online (Sandbox Code Playgroud)\n

看起来我的 django-cors-headers 设置是错误的。但我可以获取我的 JWT 令牌。以下请求成功。

\n
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/users/1.\n(Reason: CORS header \xe2\x80\x98Access-Control-Allow-Origin\xe2\x80\x99 missing).\nStatus code: 301.\n
Run Code Online (Sandbox Code Playgroud)\n

小智 6

除了仔细检查中间件的加载顺序之外,我几乎尝试了所有方法...我通过以下加载顺序解决了我的问题

MIDDLEWARE = [
    # Default
    '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',
    # CORS
    'corsheaders.middleware.CorsMiddleware',
]
Run Code Online (Sandbox Code Playgroud)

... 到

MIDDLEWARE = [
    # CORS
    'corsheaders.middleware.CorsMiddleware',
    # Default
    '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',
]
Run Code Online (Sandbox Code Playgroud)

我知道这一定是简单的事情,但现在我觉得自己像个大白痴......