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

React注册表单无法提交数据,反复出现Axios错误求助

React注册表单Axios错误排查与修复方案

问题核心原因

  1. 前端请求地址错误:Axios未指定后端完整URL,默认向前端所在的3000端口发送请求,而后端运行在4000端口,导致请求目标错误。
  2. 后端请求体解析失效:express.json()中间件放在路由定义之后,无法解析POST请求的JSON格式数据,导致req.body为空。
  3. 响应格式错误:后端res.json()传入多个参数,该方法仅接受单个对象/值,导致响应内容异常。
  4. 缺少错误处理:前端未捕获Axios请求错误,无法明确报错原因;后端未处理MongoDB连接及数据库操作的错误。

前端代码修复

主要修改点:

  • 指定完整的后端请求URL
  • 添加错误捕获逻辑,便于排查问题
  • 完善表单输入的基础属性(提升兼容性)
import { useState } from "react";
import { Link } from "react-router-dom";
import axios from 'axios';

export default function RegisterPage() {
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [errorMsg, setErrorMsg] = useState('');
    
    async function registerUser(e) {
        e.preventDefault();
        setErrorMsg('');
        try {
            const response = await axios.post('http://192.168.1.106:4000/register', {
                name,
                email,
                password,
            });
            console.log('注册成功:', response.data);
            // 注册成功后的逻辑,比如跳转到登录页
        } catch (err) {
            setErrorMsg(err.response?.data?.message || '注册失败,请稍后重试');
            console.error('注册错误:', err);
        }
    }

    return (
        <div className="mt-4 grow flex items-center justify-around">
            <div className="mb-30">
                <h1 className="text-4xl text-center mb-4">Register</h1>
                {errorMsg && <div className="text-red-500 text-center mb-2">{errorMsg}</div>}
                <form className="max-w-md mx-auto" onSubmit={registerUser}>
                    <input 
                        type="text"
                        name="name"
                        placeholder="Ali Khan"
                        value={name}
                        onChange={e => setName(e.target.value)}
                        required
                    />
                    <input 
                        type="email"
                        name="email"
                        placeholder="your@email.com"
                        value={email}
                        onChange={e => setEmail(e.target.value)}
                        required
                    />
                    <input 
                        type="password"
                        name="password"
                        placeholder="password"
                        value={password}
                        onChange={e => setPassword(e.target.value)}
                        required
                    />
                    <button className="Primary" type="submit">Register</button>
                    <div className="text-center py-2 text-gray-500">
                        Already a Member? <Link className="underline" to={'/login'}>Login</Link>
                    </div>
                </form>
            </div>
        </div>
    );
}

后端代码修复

主要修改点:

  • 将express.json()移至路由定义之前,确保能解析JSON请求体
  • 修复res.json()的参数格式,返回完整的用户数据对象
  • 处理MongoDB连接错误,确认数据库连接状态
  • 恢复User模型并实现用户创建逻辑(包含密码加密)
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const User = require('./models/User.js');
require('dotenv').config();
const bcrypt = require('bcrypt');

const app = express();
const bcryptSalt = bcrypt.genSaltSync(10);

// CORS配置
app.use(cors({
    credentials: true,
    origin: 'http://192.168.1.106:3000',
}));

// 解析JSON请求体,必须放在路由之前
app.use(express.json());

// MongoDB连接错误处理
mongoose.connect(process.env.MONGO_URL)
    .then(() => console.log('MongoDB连接成功'))
    .catch(err => console.error('MongoDB连接失败:', err));

app.get('/test', (req, res) => {
    res.json({ message: 'test is ok' });
});

app.post('/register', async (req, res) => {
    try {
        const { name, email, password } = req.body;
        // 创建用户,加密密码
        const userDoc = await User.create({
            name,
            email,
            password: bcrypt.hashSync(password, bcryptSalt),
        });
        // 返回用户数据(注意不要返回密码)
        res.json({ 
            id: userDoc._id,
            name: userDoc.name,
            email: userDoc.email
        });
    } catch (err) {
        // 处理重复邮箱等数据库错误
        res.status(422).json({ message: err.message });
    }
});

app.listen(4000, () => {
    console.log('后端服务运行在4000端口');
});

补充:User模型文件(models/User.js)

确保创建该模型文件,定义用户集合结构:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: String,
    email: { type: String, unique: true },
    password: String,
});

module.exports = mongoose.model('User', userSchema);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:33:20