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

开发计算机辅助学习应用时遇axios 403请求失败错误求助

问题描述

我正在开发一款计算机辅助学习(Computer Aided Learning)应用,跟着系列视频教程实现教师注册功能时,向API提交数据总会触发axios 403请求失败错误。之前API能正常接收数据,完成新代码变更后才出现这个问题,试了多种方法都没解决。相关代码如下:

import {Link} from 'react-router-dom';
import { useEffect, useState } from 'react';
import axios from 'axios';

const baseUrl='http://127.0.0.1:8000/api/teacher/';
    
function TeacherRegister(){
        const [teacherData, setteacherData]=useState({
            'full_name':'',
            'email':'',
            'password':'',
            'mobile_no':'',
            'skills':'',
            'status':''
        });
        //Change element value
        const handleChange=(event)=>{
            setteacherData({
                ...teacherData,
                [event.target.name]:event.target.value
            });
        }
        //Submit Form
        const submitForm=()=>{
            const teacherFormData=new FormData();
            teacherFormData.append("full_name", teacherData.full_name)
            teacherFormData.append("email", teacherData.email)
            teacherFormData.append("password", teacherData.password)
            teacherFormData.append("mobile_no", teacherData.mobile_no)
            teacherFormData.append("skills", teacherData.skills)

            try{
                axios.post(baseUrl,teacherFormData).then((response)=>{
                    setteacherData({
                        'full_name':'',
                        'email':'',
                        'password':'',
                        'mobile_no':'',
                        'skills':'',
                        'status':'success'

                    });
                });
            }catch(error){
                console.log(error);
                setteacherData({'status':'error'})
            }
        };
            
        //end Submit

        useEffect(()=>{
            document.title='Teacher Register';
        });

        return(
            <div className="container mt-4">
                <div className="row"> 
                <div className="col-6 offset-3">

                {teacherData.status=='success' && <p class="text-success">Thanks for your registration!</p>}
                    {teacherData.status=='error' && <p class="text-danger">Something wrong happened!</p>}

                    <div className="card">
                        <h5 className="card-header">Teacher Register</h5>
                        <div className="card-body">
                        <form>
                            <div className="mb-3">
                                <label htmlFor="full_name" className="form-label">Full Name</label>
                                <input value={teacherData.full_name} onChange={handleChange} type="text" className="form-control" name="full_name" aria-describedby="emailHelp"/>                            
                            </div>
                            <div className="mb-3">
                                <label htmlFor="email" className="form-label">Email</label>
                                <input value={teacherData.email} onChange={handleChange} type="email" className="form-control" name="email" aria-describedby="emailHelp"/>                            
                            </div>
                            <div className="mb-3">
                                <label htmlFor="password" className="form-label">Password</label>
                                <input value={teacherData.password} onChange={handleChange} type="password" className="form-control" name="password"/>
                            </div>                        
                            {/* <div className="mb-3 form-check">
                                <input type="checkbox" className="form-check-input" id="exampleCheck1"/>
                                <label className="form-check-label" htmlFor="exampleCheck1">Remember Me</label>
                            </div> */}
                            <div className="mb-3">
                                <label htmlFor="mobile_no" className="form-label">Mobile Number</label>
                                <input value={teacherData.mobile_no} onChange={handleChange} type="number" className="form-control" name="mobile_no"/>
                            </div>
                            <div className="mb-3">
                                <label htmlFor="skills" className="form-label">Skills</label>
                                <textarea value={teacherData.skills} onChange={handleChange} name="skills" className="form-control"></textarea>                            
                            </div>
                            <button onClick={submitForm} type="submit" className="btn btn-primary">Register</button>
                            </form>

                        </div>
                        </div>
                    </div>
                </div>
        </div>
    )
}
export default TeacherRegister;
排查与修复方案

1. 阻止表单默认提交行为

按钮type="submit"会触发表单默认提交逻辑,导致页面刷新或请求异常,先在提交函数中阻止默认行为:

const submitForm=(event)=>{
    event.preventDefault(); // 新增该行阻止默认提交
    const teacherFormData=new FormData();
    // 剩余代码不变
};

同时修改按钮的事件传递:

<button onClick={(e) => submitForm(e)} type="submit" className="btn btn-primary">Register</button>

2. 补充CSRF令牌(针对Django等后端框架)

多数后端框架默认启用CSRF保护,用FormData提交时未携带令牌会触发403,可通过以下方式添加:

// 从Cookie中获取CSRF令牌
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 在请求中添加令牌
axios.post(baseUrl, teacherFormData, {
    headers: {
        'X-CSRFToken': getCookie('csrftoken'),
    }
})

3. 匹配后端期望的请求格式

如果之前用JSON格式提交,现在换成FormData可能导致后端解析失败,可改回JSON提交:

try{
    axios.post(baseUrl, teacherData, {
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken'), // 按需添加CSRF令牌
        }
    }).then((response)=>{
        // 成功逻辑不变
    });
}catch(error){
    // 错误逻辑不变
}

4. 检查后端权限配置

确认后端注册接口是否新增了认证规则、IP白名单或请求频率限制,导致请求被拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:41:00