Node.js项目编辑用户出现Cannot POST /update-user错误如何解决
问题原因
- 表单无提交地址:
update-user.ejs中的<form>标签未设置action属性,提交时默认向当前页面路径/update-user发送POST请求,而路由配置中仅定义了GET /update-user的页面渲染路由,没有对应处理POST请求的路由,直接触发Cannot POST /update-user错误。 - 请求方法不匹配:后端定义的用户更新接口为
PUT /api/users/:id,但原生HTML表单仅支持GET、POST两种请求方法,无法直接发送PUT请求。 - 控制器更新逻辑缺失异常捕获:
controller.js中的update方法未添加catch块,数据库操作出错时会无响应。
解决方法
提供两种可选方案:
方案1:AJAX提交(推荐,符合RESTful规范)
- 在
update-user.ejs的页脚(_footer.ejs引入后)添加如下JS代码,拦截表单默认提交行为,发送PUT请求:
<script> document.getElementById('update_user').addEventListener('submit', async function(e) { e.preventDefault(); // 获取用户ID const userId = document.querySelector('input[name="id"]').value; // 组装表单数据 const formData = new FormData(this); const payload = Object.fromEntries(formData.entries()); // 发送更新请求 const res = await fetch(`/api/users/${userId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); // 处理响应 if (res.ok) { window.location.href = '/'; // 更新成功跳转到用户列表页 } else { alert('用户更新失败,请检查输入内容后重试'); } }) </script>
- 补全
controller.js中update方法的异常捕获,新增new: true配置返回更新后的数据:
//Update a new identified user by user id exports.update = (req, res) => { if(!req.body){ return res.status(400).send({ message:"data to update content can not be empty" }); } const id = req.params.id; Userdb.findByIdAndUpdate(id, req.body,{ useFindAndModify: false, new: true }) .then(data=>{ if(!data){ res.status(404).send({ message:`User not found with id ${id}` }); }else{ res.send(data); } }) .catch(err => { res.status(500).send({message: err.message || "Error occured while updating user information"}); }); };
方案2:适配原生表单提交(无需额外JS代码,适合简单场景)
- 修改
update-user.ejs的form标签,指定提交地址:
<form method="POST" action="/update-user/<%= user._id %>" id="update_user">
- 在
router.js中新增POST路由处理表单提交请求:
route.post('/update-user/:id', controller.update);
- 修改
controller.js中update方法的成功响应逻辑,更新完成后跳转回用户列表页:
// 把原update方法中的 res.send(data) 替换为如下代码 res.redirect('/');
额外注意事项
model.js中模型命名存在笔误:mongoose.model('userbd',schema)应为mongoose.model('userdb',schema),虽不影响本次报错,但会导致数据库集合名异常,建议同步修正。
内容的提问来源于stack exchange,提问作者PocketPixie
相关产品推荐
相关产品推荐

