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

React+Mongoose开发中CastError问题:使用Context API传递邮箱至后端查询MongoDB失败

解决Mongoose CastError:前端传值与后端接收不匹配问题

问题根源

你遇到的CastError本质是前后端数据格式不匹配:前端发送的请求体是一个包含lstate属性的对象,而后端直接把整个请求体当作邮箱字符串用于MongoDB查询,Mongoose无法将对象转换为字符串类型的email字段,因此抛出错误。

从你的控制台日志也能明确看出来:

data from account [object Object]
CastError: Cast to string failed for value "{ lstate: 'usman4276@gmail.com' }" at path "email"

后端接收到的req.body是{ lstate: 'usman4276@gmail.com' }这个对象,而非单纯的邮箱字符串。


解决方案

需要同时调整前端的请求体格式,以及后端的取值逻辑:

1. 前端修改(Account.jsx)

如果lstate本身就是邮箱字符串,你需要将请求体改为直接传递email字段,而不是包裹在lstate键下:

const Account = () => {
  const { lstate } = useContext(LoginContext);
  const LoginData = async () => {
    console.log(`my lstate in login function ${lstate}`);
    await fetch('/account', {
      method: 'POST',
      headers: { "Content-Type": "application/json" },
      // 修改这里:将lstate赋值给email字段
      body: JSON.stringify({ email: lstate })
    }).then((res) => {
      console.log(res);
    }).catch((err) => {
      console.log(err);
    })
  }
  useEffect(() => {
    LoginData();
  }, []);
}

如果lstate是一个包含email属性的对象(比如lstate = { email: 'xxx@xxx.com' }),则需要取出对应属性:

body: JSON.stringify({ email: lstate.email })

2. 后端修改(auth.js)

从请求体中正确提取email字段,而不是直接使用整个req.body对象:

router.post('/account', async (req, res) => {
  try {
    // 修改这里:取出req.body中的email属性
    const email = req.body.email;
    console.log(`data from account ${email}`);
    const data = await CustomerModel.findOne({ email: email });
    if (data) {
      return res.json(data);
    } else {
      // 建议添加无数据的响应逻辑
      return res.status(404).json({ message: "No customer found with this email" });
    }
  } catch (error) {
    console.log(error);
    // 建议添加错误响应逻辑
    return res.status(500).json({ error: error.message });
  }
})

验证修改

修改完成后:

  • 前端控制台可以查看发送的请求体,确认是{ email: 'usman4276@gmail.com' }
  • 后端控制台会打印出邮箱字符串usman4276@gmail.com,而非[object Object]
  • Mongoose会用正确的字符串查询email字段,不会再抛出CastError

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:53:15