【问题标题】:Express.js API delete route not workingExpress.js API 删除路由不起作用
【发布时间】:2017-10-23 03:26:16
【问题描述】:

我正在尝试在 express 中创建一个 API,但在 /posts/:postId 上创建删除路由时遇到错误每当我尝试使用邮递员对该路由发出删除请求时,页面只会无限加载,并且请求被中止。

这是我的/posts/:postId 路线的样子:

router.route("/:postId")
.get(controllers.getSinglePost)
.delete(function(req, res){ res.send('work'); });

controllers.getSinglePost 函数如下所示:

`

exports.getSinglePost = function(req, res){
  db.Post.findById(req.params.postId)
  .populate('comments')
  .then(post=>{
    if(!post) return res.status(404).json({message: "Post not found"});
    res.status(200).json(post);
  }).catch(err=>{
    res.status(500).json(err);
  });
}

`

我真的不明白我做错了什么。

【问题讨论】:

  • 开始工作了吗?
  • 是的。只是删除路线不起作用。
  • 你能分享一下controllers.getSinglePost函数是什么样子的吗?
  • 您是如何引用路由器的?页面无限加载是什么意思?你确定请求命中DELETE 部分吗?尝试将console.log 放入DELETE 部分

标签: node.js rest express routes http-delete


【解决方案1】:
exports.getSinglePost = function(req, res){
      db.Post.findById(req.params.postId)
      .populate('comments')
      .then(post=>{
        if(!post) return res.status(404).json({message: "Post not found"});
        res.status(200).json(post);
      }).catch(err=>{
        res.status(500).json(err);
      });
    }

【讨论】:

    【解决方案2】:

    我不明白你的意思,但你可以更改代码来完成你的工作。我用sequelize,可能不存在populate的属性。这是我的代码,成功了。

    getSinglePost = function(req, res){
      db.models.City.findById(req.params.postId)
      .then(post=>{
        if(!post) return res.status(404).json({message: "Post not found"});
        res.status(200).json(post);
      }).catch(err=>{
        res.status(500).json(err);
      });
    }
    
    app.route('/:postId')
      .get(function(req,res){
        getSinglePost(req,res)
      })
      .delete(function (req, res) {
        res.send('Update1 the book')
      })
    

    【讨论】:

      【解决方案3】:

      好的,所以似乎由于某种原因,我使用的一个名为 formidable 的 npm 包导致了这个问题。一旦我从应用程序中删除它,它就又开始工作了。很抱歉浪费你们时间。

      【讨论】:

        猜你喜欢
        • 2021-05-17
        • 2016-11-23
        • 1970-01-01
        • 2019-09-12
        • 1970-01-01
        • 2019-08-28
        • 1970-01-01
        • 1970-01-01
        • 2018-10-10
        相关资源
        最近更新 更多