Node.js用户注册时res.status(...).send(...).catch不是函数的报错原因
报错原因及修复方案
报错根本原因
res.status(...).send(...) 调用后返回的是 Express 的响应对象(Response),不是 Promise,所以没有 .catch() 方法。你错误地把错误捕获的 .catch() 绑定在了 send 方法的返回值上,这就导致了 TypeError: ...catch is not a function。
修复后的代码
bcrypt.hash(req.body.password, 10) .then((hashedPassword) => { const user = new User({ email: req.body.email, password: hashedPassword, }); // 把 catch 放在 user.save() 的 Promise 链上,而不是 res.send() 之后 user.save() .then((result) => { res.status(201).send({ message: "User created successfully", result, }); }) .catch((err) => { res.status(500).send({ message: "Error creating User", err, }); }); }) .catch((err) => { res.status(500).send({ message: "Password was not hashed successfully", err, }); });
额外优化建议(可选)
如果你的 Node.js 版本支持,可以用 async/await 重构代码,避免 Promise 嵌套,让逻辑更清晰:
// 确保外层路由处理函数是 async 函数 try { const hashedPassword = await bcrypt.hash(req.body.password, 10); const user = new User({ email: req.body.email, password: hashedPassword, }); const result = await user.save(); res.status(201).send({ message: "User created successfully", result, }); } catch (err) { // 根据错误类型区分返回信息 if (err.message.includes("hash")) { res.status(500).send({ message: "Password was not hashed successfully", err, }); } else { res.status(500).send({ message: "Error creating User", err, }); } }
内容的提问来源于stack exchange,提问作者Phills6329
相关产品推荐
相关产品推荐

