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

MERN栈CRUD系统更新功能返回AxiosError500求助

问题分析与修复方案

核心错误原因

你的500错误主要来自后端PUT接口中未定义的quantity变量,同时还有几处前端和后端的逻辑问题需要修正:


1. 修复后端PUT接口

后端代码中{ $inc: { Quantity: -quantity } }里的quantity未定义,需要从请求体中获取前端传入的值,同时要做数字校验:

const InvItem = mongoose.model('InventoryItems', schema);

// 修复GET接口(原代码误用findOneAndUpdate,应为查询接口)
app.get('/api/items/:Item', async (req, res) => {
  try {
    const item = await InvItem.findOne({ Item: req.params.Item });
    if (!item) {
      return res.status(404).send({ error: 'Item not found' });
    }
    res.send(item);
  } catch (err) {
    console.log(err);
    res.status(500).send({ error: 'Internal server error' });
  }
});

// 修复PUT接口
app.put('/api/items/:Item', async (req, res) => {
  try {
    // 从请求体获取数量并转为数字,做有效性校验
    const quantity = parseInt(req.body.Quantity, 10);
    if (isNaN(quantity)) {
      return res.status(400).send({ error: '请输入有效数字' });
    }

    const updatedItem = await InvItem.findOneAndUpdate(
      { Item: req.params.Item },
      { $inc: { Quantity: -quantity } }, // 使用正确的变量
      { new: true } // 返回更新后的文档
    );

    if (!updatedItem) {
      return res.status(404).send({ error: 'Item not found' });
    }
    res.send(updatedItem);
  } catch (err) {
    console.log(err);
    res.status(500).send({ error: 'Internal server error' });
  } 
});

2. 修复前端Axios请求

  • 输入框的值默认是字符串,需要转为数字后再发送
  • 更新state时,要取响应数据中的Quantity字段,而非整个响应对象:
// 先处理输入值,转为数字并校验
const inputQuantity = parseInt(quantityInput.value, 10);
if (isNaN(inputQuantity)) {
  console.log('请输入有效的数字');
  return;
}

axios.put('/api/items/' + selectComponent, {
    Quantity: inputQuantity
  })
  .then((response) => {
    setItems(previousItems => previousItems.map(item => {
      if (item.Item === selectComponent) {
        // 替换为更新后的Quantity值
        return { ...item, Quantity: response.data.Quantity };
      }
      return item;
    }));
  })
  .catch((error) => {
    console.log(error);
  });

其他说明

  • 后端的findOneAndUpdate第三个参数{ new: true }是正确的,确保返回更新后的文档
  • 前端和后端都做了数字校验,避免传入非数字值导致数据库操作错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:45:40