【问题标题】:i am getting an error while i am updating my data using express node.js使用 express node.js 更新数据时出现错误
【发布时间】:2021-12-20 02:25:31
【问题描述】:

我正在尝试更新我的类别名称,但是当我单击提交按钮时它给了我一个错误但是我使用邮递员测试了我的代码并且它实际上已更新但在这种情况下我必须手动传递产品的 ID。

更新类别的回调函数:

    exports.updateCategory = (req, res, next) => {

    console.log('GET update CATEGORY /update-category');

    if (!req.body) {
        return res
            .status(400)
            .send({ message: "Data to update can not be empty" })
    }

    const id = req.params.id; //req.body.id >> body means in the html/ejs file the name should be id

    categorySchema.findByIdAndUpdate(id, req.body, { userFindAndModify: false })
        .then(data => {
            if (!data) {
                res.status(404).send({ message: `Cannot Update user with ${id}` })
            }
            //updating the data
            else {
                res.render('category/edit_category.ejs', {
                    category: data //variable that i am going to use is category in the ejs
                })
            }

        })

    .catch(err => {
        res.status(500).send({ message: "Error update user information" })
    })


}

更新表格>>

    <form action='<%=`/halalMunchies/update-category/${category._id}`%>' method="post">
.
.
.
<label class="control-label" for="categoryName"> Category Name </label>
        <input type="hidden" name="id" value="" id="id">
        <input id="categoryName" class="form-control" value="<%= category.categoryName%>" name="categoryName" required autofocus="autofocus" />

router.js

    //PUT UPDATE CATEGORY

router.put('/update-category/:id', categoriesController.updateCategory);

router.get('/update-category/:id', categoriesController.updateCategory);

页面上的错误信息是:

Cannot POST /halalMunchies/update-category/618632e3a5ad00fa5368ad5c

【问题讨论】:

  • 你得到的实际错误是什么?
  • 网上的错误信息是Cannot POST /halalMunchies/update-category/618632e3a5ad00fa5368ad5c

标签: node.js express mongoose


【解决方案1】:

正如错误消息告诉您的那样,您没有在路由器中提供post 端点。由于您在表单中使用 post 方法,因此您需要在 router.js 中添加以下内容:

router.post('/update-category/:id', categoriesController.updateCategory);

【讨论】:

  • 非常感谢 Eol,它有效。但是我还有一个问题,我想在我点击更新页面中的提交 btn 后,我希望它引导我到另一个页面。
  • 很高兴为您提供帮助 - 因为这似乎是一个新问题,您能在新问题中描述一下吗?
  • 是的,我肯定会发布这个问题,但你能帮我解决这个问题吗? stackoverflow.com/q/69870869/15454800
猜你喜欢
  • 2020-11-20
  • 2021-08-24
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2018-09-27
  • 2023-03-22
  • 2012-05-26
  • 1970-01-01
相关资源
最近更新 更多