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

Django4.1+React项目POST请求遇CSRF cookie未设置403错误求助

修复React + Django POST请求CSRF 403错误

问题梳理

GET请求正常返回200,但POST请求触发Forbidden (CSRF cookie not set.)错误,Chrome控制台Application面板无法找到CSRF Cookie。核心问题集中在React端请求凭证配置、异步逻辑顺序错误,以及部分代码拼写疏漏。

具体修复步骤

1. 配置axios跨域携带凭证

axios默认不会携带跨域Cookie,需开启withCredentials: true确保浏览器能保存和发送CSRF Cookie:

  • 全局配置(推荐):在项目入口文件(如index.js)添加:
    import axios from 'axios';
    axios.defaults.withCredentials = true;
    
  • 单个请求配置:若不想全局设置,可在获取CSRF和注册请求中单独添加:
    // csrfToken.js中fetchData函数
    await axios.get(`${process.env.REACT_APP_API_URL}/accounts/csrf-cookie`, { withCredentials: true });
    
    // src/actions/auth.js的register请求配置
    const config = {
        withCredentials: true,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-CSRFToken': Cookies.get('csrftoken')
        }
    };
    

2. 修正csrfToken.js的异步逻辑与拼写错误

原代码在异步请求未完成时就获取Cookie,且存在大小写拼写错误:

// 修正后的useEffect逻辑
useEffect(() => {
    const fetchData = async () => {
        try {
            await axios.get(`${process.env.REACT_APP_API_URL}/accounts/csrf-cookie`, { withCredentials: true });
            // 请求完成后再获取并设置Cookie
            setcsrftoken(getCookie('csrftoken'));
            console.log('success');
        } catch (err) {
            console.error(err);
        }
    };

    fetchData();
}, []);

同时修正组件返回的input值,确保与state变量一致:

return (
    <input type='hidden' name='csrfmiddlewaretoken' value={csrftoken} />
);

3. 修复Django视图的拼写错误

GetCSRFToken视图中permissions_classes拼写错误,且应为数组格式:

@method_decorator(ensure_csrf_cookie, name='dispatch')
class GetCSRFToken(APIView):
    permission_classes = [permissions.AllowAny, ] # 修正拼写和格式

    def get(self, request, format=None):
        return Response({'success': 'CSRF Cookie set'})

4. 确保注册请求在CSRF Cookie获取完成后执行

在Register组件中添加状态判断,避免提前提交请求:

// 在Register组件中添加状态
const [csrfReady, setCsrfReady] = useState(false);

// 组件挂载时获取CSRF Cookie
useEffect(() => {
    const getCsrf = async () => {
        await axios.get(`${process.env.REACT_APP_API_URL}/accounts/csrf-cookie`, { withCredentials: true });
        setCsrfReady(true);
    };
    getCsrf();
}, []);

// 禁用提交按钮直到CSRF Cookie准备完成
<Button type="submit" disabled={!csrfReady}>
    Create User
</Button>

验证修复

  1. 重启Django和React开发服务
  2. 打开注册页面,查看Chrome控制台Application面板是否存在csrftoken Cookie
  3. 提交注册表单,检查终端是否返回200响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:25:01