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

Luiztools教程实操:Node.js+MongoDB实现CRUD时编辑客户返回404错误排查

问题原因排查
  • 你在views/index.ejs中给客户名称配置的编辑跳转是<a href="/edit/<%= customer._id %>">,属于GET请求访问/edit/:id路径
  • 但routes/index.js里只定义了router.post('/edit/:id')的编辑提交处理路由,没有对应GET请求的路由,所以访问时直接返回404。
解决方案

1. 新增编辑页GET路由

在routes/index.js里新增GET类型的/edit/:id路由,用来加载带原有数据的编辑表单,代码如下:

router.get('/edit/:id', async (req, res, next) => {
  const id = req.params.id;
  try {
    const doc = await global.db.findOne(id);
    // 复用new.ejs模板,指定提交动作为对应id的编辑接口,同时传入客户原有数据
    res.render('new', { title: '编辑客户', doc, action: `/edit/${id}` });
  } catch (err) {
    next(err);
  }
});

可以将这段代码插在router.post('/new')和router.post('/edit/:id')两个路由之间。

2. 验证效果

重启项目后点击客户名称即可正常加载编辑表单,修改信息点击保存会提交到POST类型的/edit/:id路由执行更新,跳转回首页后就能看到修改后的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:15:02