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

React中Axios发送PUT请求提交表单后端接收空数据如何解决?

问题原因

  • 请求体封装错误:axios.put() 方法的第二个参数直接对应请求体内容,你当前额外包裹了一层{data: orders},导致后端req.body拿到的结构是{data: {ticker:xxx, ...}},直接解构ticker等字段自然为空。
  • 路径参数拼接错误:后端通过req.params.email获取邮箱,你的请求URL错误写成http://localhost:8081/api/auth/order/:email?=${email},最终传递给后端的req.params.email值为固定字符串:email,而非实际填写的邮箱值,就算请求体正确也找不到对应用户。
  • (次要问题)后端返回逻辑有语法问题:res.status(200).send(user).json(...) 同时调用send和json会导致返回格式异常,且返回信息中引用的orders变量未定义,会触发运行时报错。

解决方案

1. 前端代码修改

修正请求URL和请求体传递逻辑,修改后handleSubmit代码如下:

const handleSubmit = async (e) =>{
  e.preventDefault()
  const orders = {
    ticker,
    amount,
    price,
    date,
    comments
  }
  console.log(orders)
  try{
    // 修正路径参数,直接传递orders作为请求体
    const res = await axios.put(`http://localhost:8081/api/auth/order/${email}`, orders)
    console.log(res)
    console.log(`Order saved to ${email}'s account`)
  }catch(e){
    console.log(e)
  }
}

2. 后端代码优化

修正返回逻辑和变量引用问题:

exports.addOrder = async (req, res) => {
  const {email} = req.params
  const { ticker, amount, price, date, comments } = req.body;
  try{
    const orderItem = { ticker, amount, price, date, comments }
    const user = await User.findOneAndUpdate(
      { email: email },
      { $push: { orders: orderItem } }
    )
    if (!user) {
      return res.status(404).json({message: '用户不存在'})
    }
    // 不要同时调用send和json,统一用json返回
    res.status(200).json({
      user,
      message: `Order: ${JSON.stringify(orderItem)} \n has been added to ${user.email}`
    });
  }catch(error) {
    res.status(400).json({
      error: error.message
    })
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:54:04