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文件:- 在
INSTALLED_APPS中添加:INSTALLED_APPS = [ # ... 其他已有应用 'corsheaders', ] - 在
MIDDLEWARE中添加(必须放在CommonMiddleware之前):MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # ... 其他已有中间件 ] - 添加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
相关产品推荐
相关产品推荐

