Node.js+Angular CRUD应用更新功能异常求助
Node.js + Angular CRUD 更新功能故障排查与修复
问题现象
新增、删除、查看功能正常,点击更新表单提交时:
- 浏览器控制台报错:
Failed to load resource: net::ERR_CONNECTION_REFUSED :9002/user/update/undefined:1
- Node.js服务器崩溃,命令行报错:
node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */); ^ [UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "false".] { code: 'ERR_UNHANDLED_REJECTION' }
问题根源与修复方案
1. Angular端:ID未正确赋值导致请求URL无效
浏览器报错中的undefined表明currentEmployeeID变量未被正确赋值,生成了无效请求URL,触发连接拒绝,进而引发后续服务器异常。
修复步骤:
- 确认模板中更新按钮是否正确绑定
setUpdate方法并传递完整员工数据对象,示例:<button (click)="setUpdate(employee)">编辑</button> - 修改
UpdateRecords方法,添加ID校验、改用模板字符串拼接URL(避免拼接错误),并补充错误处理:UpdateRecords() { console.log("当前员工ID:", this.currentEmployeeID); // 验证ID是否有效 if(!this.currentEmployeeID) { alert("请选择要更新的员工"); return; } let bodyData = { "first_name" : this.first_name, "last_name" : this.last_name, "email" : this.email, "password" : this.password, }; this.http.patch(`http://localhost:9002/user/update/${this.currentEmployeeID}`, bodyData) .subscribe({ next: (resultData: any) => { console.log(resultData); alert("员工信息已更新"); // this.getAllEmployee(); // 可选:更新列表显示 }, error: (err) => { console.error("更新失败:", err); alert("更新失败,请检查服务器状态"); } }); }
2. Node.js端:未处理Promise拒绝导致服务器崩溃
数据库服务函数中reject(false)未传递具体错误信息,且路由层未捕获Promise拒绝,触发UncaughtPromiseRejection直接导致服务器崩溃。
修复步骤:
- 修改数据库服务函数,reject时传递具体错误对象,并添加
{new: true}选项返回更新后的文档:module.exports.updateOneUserDBService = (id, userDetais) => { console.log(userDetais); return new Promise(function myFn(resolve, reject) { // {new: true} 返回更新后的文档,方便前端验证结果 userModel.findByIdAndUpdate(id, userDetais, {new: true}, function returnData(error, result) { if(error) { reject(error); // 传递具体错误对象,便于排查 } else { resolve(result); } }); }); } - 在调用该服务的路由层添加错误捕获(以Express路由为例):
router.patch('/user/update/:id', async (req, res) => { try { const userId = req.params.id; const userDetails = req.body; const result = await updateOneUserDBService(userId, userDetails); if(!result) { return res.status(404).json({message: "员工不存在"}); } res.status(200).json(result); } catch(err) { console.error("数据库更新失败:", err); res.status(500).json({message: "服务器内部错误"}); } });
额外优化建议
- Angular端在
save方法中增加ID校验,避免无效调用:save() { if(this.currentEmployeeID === '') { this.register(); } else if (!this.currentEmployeeID) { alert("请选择要更新的员工"); } else { this.UpdateRecords(); } } - Node.js端全局捕获未处理的Promise拒绝,防止服务器崩溃:
process.on('unhandledRejection', (err) => { console.error("未处理的Promise拒绝:", err); // 可选:执行服务器重启等应急操作 });
内容的提问来源于stack exchange,提问作者nanda kumar
相关产品推荐
相关产品推荐

