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

React+Node.js表单提交问题:登录表单404且无数据发送

登录表单提交404错误及数据未发送问题排查与修复

问题概述

使用Redux Toolkit处理React登录表单时,提交触发404服务器错误,控制台显示表单未发送任何数据。后端API会在用户不存在时返回404,但当前核心问题是请求未正确传递数据或路径错误。


前端核心修复点

1. 修复axios请求路径

当前请求路径auth/login为相对路径,会默认发送到前端域名下,而非后端API地址。需补充完整API基础路径:

// 方式1:直接拼接完整地址
axios.post(`${process.env.REACT_APP_API_URL}/auth/login`, LoginData)

// 方式2:全局配置axios baseURL(推荐)
// 在项目入口文件(如index.js)添加
import axios from 'axios';
axios.defaults.baseURL = process.env.REACT_APP_API_URL;

2. 移除冗余状态,正确使用react-hook-form

你同时用useState和react-hook-form维护表单状态,易导致数据不同步。直接使用react-hook-form收集的表单数据即可:

// 移除冗余的useState
// const [email, setEmail] = useState("");
// const [password, setPassword] = useState("");

const onSubmit = async (data) => {
  setLoading(true);
  dispatch(loginStart());
  console.log(data); // 这里可查看表单实际数据
  try {
    const res = await axios.post('/auth/login', data);
    setLoading(false);
    dispatch(loginSuccess(res.data));
  } catch (error) {
    setLoading(false);
    dispatch(loginFailure()); // 修复:调用action函数(原代码少了括号)
    console.error('登录错误详情:', error.response?.data || error.message);
  }
};

同时移除输入框的onChange,仅保留react-hook-form的register:

<input
  type="email"
  name="email"
  className="form-control fs-13px h-45px"
  id="emailAddress"
  placeholder="Email Address"
  {...register("email", { required: true })}
/>

3. 修复Redux action调用错误

原代码中dispatch(loginFailure);未执行函数,需改为dispatch(loginFailure());才能触发失败action。


后端验证补充

1. 确认请求体解析中间件

确保后端已配置express.json()解析JSON请求体,否则req.body会为空:

// 在express app实例中添加
app.use(express.json());

2. 添加日志排查请求数据

在登录接口中打印请求体,确认是否收到前端数据:

exports.login = async (req, res, next) => {
  try {
    console.log('收到登录请求体:', req.body); // 打印请求体排查
    const user = await UserModel.findOne({ email: req.body.email });
    if (!user) return next(createError(404, "User not found!"));

    const isCorrect = await bcrypt.compare(req.body.password, user.password);
    if (!isCorrect) return next(createError(400, "Wrong credentials"));

    const token = jwt.sign({ id: user._id }, process.env.JWT);
    const { password, permissions, ...others } = user._doc;
    res
      .cookie("access_token", token, {
        httpOnly: true,
      })
      .status(200)
      .json(others);
  } catch (err) {
    next(err);
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:20:24