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

React使用Axios向phpMyAdmin插入数据时遇Axios Network Error求助

React + Axios 插入MySQL数据库报错修复指南

问题描述

练习用React结合Axios将表单数据插入phpMyAdmin管理的MySQL数据库时,提交表单出现Axios Network Error,错误截图如下:
Axios Network Error

以下是代码问题分析及修改方案:


一、React组件代码修正

问题点:

  1. 前端无用引入cors模块(CORS是后端配置项,前端不需要)
  2. 缺少Axios请求的错误捕获逻辑

修改后的代码:

import { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";

function AddStudent(){
    let history = useNavigate();
    const [student, setStudent] = useState({
        first_name:"",
        last_name:"",
        email:""
    })
    const {first_name, last_name, email} = student;

    const handleChange = (e)=>{
        setStudent({...student,[e.target.name]: e.target.value})
    }

    const submitForm = async (e) =>{
        e.preventDefault();
        console.log(student)
        await axios.post("http://localhost/renting_website/insert.php", student)
        .then((result) =>{
            console.log(result);
            if(result.data.status === 'valid'){
                history('/ListStudent')
            }
            else{
                alert('添加过程出现问题,请检查所有内容')
            }
        })
        // 新增错误捕获,方便排查问题
        .catch(err => {
            console.error('请求错误:', err);
            alert('网络请求失败,请检查后端服务是否正常')
        })
    }
    return(
        <form onSubmit = {e => submitForm(e)}>
            <div className="box_size">
                <div className="row">
                    <div className="col-md-12 text-center">
                        <h1>添加学生</h1>
                    </div>
                </div>
                <div className="row">
                    <div className="col-md-6">名字</div>
                    <div className="col-md-6">
                        <input type='text' name='first_name' className="form-control" 
                        value ={first_name} onChange={e => handleChange(e)}/>
                    </div>
                </div>
                <div className="row">
                    <div className="col-md-6">姓氏</div>
                    <div className="col-md-6">
                        <input type='text' name='last_name' className="form-control" 
                        value ={last_name} onChange={e => handleChange(e)}/>
                    </div>
                </div>
                <div className="row">
                    <div className="col-md-6">邮箱</div>
                    <div className="col-md-6">
                        <input type='email' name='email' className="form-control" 
                        value ={email} onChange={e => handleChange(e)}/>
                    </div>
                </div>
                <div className="row">
                    <div className="col-md-12">
                        <input type='submit' name='submit' className="btn btn-warning"  value="添加学生"/>
                    </div>
                </div>  
            </div>       
        </form>     
    )
}

export default AddStudent;

二、insert.php代码修正(核心错误集中处)

问题点:

  1. PHP标签语法错误(开头<?php>、结尾<?>均不正确)
  2. CORS头重复定义,且拼写错误(X-Requsted-With应为X-Requested-With)
  3. file_get_content函数名少了s,语句末尾缺分号
  4. 执行SQL用了连接函数mysqli_connect,正确应为mysqli_query
  5. 变量拼写错误($reponse应为$response)
  6. 存在SQL注入风险,未用预处理语句
  7. 多处语句末尾缺分号

修改后的代码:

<?php
// 配置CORS,仅允许React开发域名访问
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

include('db-connect.php');

// 先检查数据库连接状态
if (!$con) {
    $response = array('status' => 'invalid', 'msg' => '数据库连接失败');
    echo json_encode($response);
    exit;
}

// 解析JSON请求数据,转成数组避免对象访问问题
$data = json_decode(file_get_contents("php://input"), true);

// 校验必填字段
if(isset($data['first_name']) && isset($data['last_name']) && isset($data['email'])){
    $first_name = $data['first_name'];
    $last_name = $data['last_name'];
    $email = $data['email'];

    // 用预处理语句防止SQL注入
    $sql = "INSERT INTO registration(first_name, last_name, email) VALUES(?, ?, ?)";
    $stmt = mysqli_prepare($con, $sql);
    mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name, $email);
    
    if(mysqli_stmt_execute($stmt)){
        $response = array('status' => 'valid');
        echo json_encode($response);
    } else {
        $response = array('status' => 'invalid', 'msg' => mysqli_error($con));
        echo json_encode($response);
    }
    mysqli_stmt_close($stmt);
} else {
    $response = array('status' => 'invalid', 'msg' => '缺少必填字段');
    echo json_encode($response);
}

mysqli_close($con);
?>

三、db-connect.php补充连接检查

<?php
$serverName = "localhost";
$userName = "root";
$password = "";
$dbName = "renting";

$con = mysqli_connect($serverName, $userName, $password, $dbName);

// 检查数据库连接是否成功
if (!$con) {
    die("数据库连接失败: " . mysqli_connect_error());
}
?>

额外排查步骤

  1. 确保XAMPP/WAMP等服务器正在运行,直接访问http://localhost/renting_website/insert.php,应返回JSON格式错误提示(说明PHP文件能被正常解析)
  2. 检查registration表是否存在,first_name、last_name、email字段名及类型是否匹配
  3. 打开浏览器控制台→Network标签,查看请求状态码和响应内容,进一步定位问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:25:55