You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13调用Django后端API遇CORS错误求助

解决Next.js 13 + RTK Query + Django后端的CORS认证头问题

错误详情

Access to fetch at 'http://localhost:8000/user/create/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

解决方案

1. 后端Django配置(核心)

使用django-cors-headers库处理CORS规则:

  • 安装依赖:
    pip install django-cors-headers
    
  • 修改settings.py文件:
    1. 在INSTALLED_APPS中添加:
      INSTALLED_APPS = [
          # ... 其他已有应用
          'corsheaders',
      ]
      
    2. 在MIDDLEWARE中添加(必须放在CommonMiddleware之前):
      MIDDLEWARE = [
          'corsheaders.middleware.CorsMiddleware',
          'django.middleware.common.CommonMiddleware',
          # ... 其他已有中间件
      ]
      
    3. 添加CORS关键配置:
      # 允许前端域名跨域请求
      CORS_ALLOWED_ORIGINS = [
          "http://localhost:3000",
          "http://127.0.0.1:3000",
      ]
      # 开启凭证允许,对应错误要求的头设置
      CORS_ALLOW_CREDENTIALS = True
      

2. 前端RTK Query配置

确保API切片的baseQuery明确设置凭证模式,与后端配置匹配:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const userApi = createApi({
  reducerPath: 'userApi',
  baseQuery: fetchBaseQuery({
    baseUrl: 'http://localhost:8000/user/',
    credentials: 'include', // 必须设置,和后端CORS_ALLOW_CREDENTIALS=true对应
  }),
  endpoints: (builder) => ({
    register: builder.mutation({
      query: ({ name, mobile, email, password, password2 }) => ({
        url: '/create/',
        method: 'POST',
        body: { name, mobile, email, password, password2 },
      }),
    }),
  }),
});

export const { useRegisterMutation } = userApi;

额外检查项

  • 确认Django的ALLOWED_HOSTS包含localhost或127.0.0.1:
    ALLOWED_HOSTS = ['localhost', '127.0.0.1']
    
  • 若启用Django CSRF保护,前端需在请求头中携带CSRF Token:
    读取cookie中的csrftoken值,在请求头添加X-CSRFToken字段即可。

内容的提问来源于stack exchange,提问作者Shivam Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 09:02:48