i am trying to update my category name but when i click on the submit button it gives me an error however i tested my code using postman and it actually updated but in that case i have to pass the product's id manually.
the callback function of the update category:
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" })
})
}
the update form >>
<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" />
the router.js
//PUT UPDATE CATEGORY
router.put('/update-category/:id', categoriesController.updateCategory);
router.get('/update-category/:id', categoriesController.updateCategory);
the error message on page is :
Cannot POST /halalMunchies/update-category/618632e3a5ad00fa5368ad5c
CodePudding user response:
As the error message tells you, you did not provide a post
endpoint in your router. Since you're using the post
method in your form, you need to add the following in your router.js:
router.post('/update-category/:id', categoriesController.updateCategory);