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

Node.js+Express项目Postman发Delete请求返回404问题求助

问题排查及修复方案

1. 路由路径缺失前置斜杠导致404

你当前的DELETE路由定义没有加路径开头的/,Express无法匹配到请求路径,直接返回404:

// 错误写法
router.delete('api/entries/:id', function(req, res, next){

修复为:

router.delete('/api/entries/:id', function(req, res, next){

2. 删除逻辑语法错误

你当前的删除代码存在两处语法错误:

  • findByIdAndRemove 方法直接传入id字符串即可,不需要包裹为{_id: id}的对象(如果要用对象传参请切换为findOneAndDelete方法)
  • res.send(entry) 写在了then回调外面,同时括号闭合顺序错误,导致entry变量无法访问,也不会在数据库操作完成后返回响应
// 错误写法
Entry.findByIdAndRemove({_id: req.params.id}).then(function(entry){}).res.send(entry);

修复为:

Entry.findByIdAndRemove(req.params.id)
  .then(function(entry){
    // 校验是否找到对应数据
    if(!entry) return res.status(404).send({message: '待删除条目不存在'})
    res.send(entry)
  })
  .catch(next)

修复后的完整路由代码参考

router.delete('/api/entries/:id', function(req, res, next){
  Entry.findByIdAndRemove(req.params.id)
    .then(function(entry){
      if(!entry) return res.status(404).json({error: '条目不存在'})
      res.json(entry)
    })
    .catch(next)
})

修复后在Postman发送DELETE请求时,确认请求地址为http://localhost:3001/api/entries/[你的数据id]即可正常执行删除操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:36:04