MERN栈axios提交注册请求报accLevel转Number失败Postman测试正常
问题原因
你出现该错误的核心原因是前端发送axios请求时没有携带构造好的用户参数:
你在前端代码中已经组装好了newUser对象,但是调用axios.post时只传了接口地址,没有把newUser作为第二个参数传入,导致后端收到的req.body是空对象,所有字段都是undefined:
- username和password为空,触发必填校验报错
- 空值传给
Number(req.body.accLevel)转成NaN,触发Mongoose数值类型转换报错
Postman测试正常是因为你手动填写了请求体参数,和接口逻辑本身无关。
修复方案
第一步:修复前端axios请求代码
找到createUserAccount.jsx中的axios请求部分,补充请求体参数:
// 原错误代码 axios.post("http://localhost:8070/user/createUserAccount").then(()=>{ // 修改为 axios.post("http://localhost:8070/user/createUserAccount", newUser).then(()=>{
可选后端优化(避免类似问题)
如果允许用户不传accLevel字段、直接用Schema默认值,可以修改后端逻辑,避免空值转NaN的问题:
//createUserAccount接口逻辑修改 router.route("/createUserAccount").post((req,res) => { const {username, password, accType, accLevel} = req.body; const userData = { username, password, accType } // 仅当accLevel有值时才加入参数,否则用Schema默认值1 if(accLevel) userData.accLevel = Number(accLevel); const newUser = new User(userData); // 后续保存逻辑不变 })
修复后重新测试即可正常提交。
内容的提问来源于stack exchange,提问作者Constalation
相关产品推荐
相关产品推荐

