Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Update and Delete Entries

Unusual behavior with route parameter id using nodeJs on POST request

@ 4:20 Guil goes over the delete and setting it.

take a look at the two codes below --

Here is the original code (modified for testing. Pay attention to the console log)

/* Delete article form. */
router.get("/:id/delete", asyncHandler(async (req, res) => {
  const article = await Article.findByPk(req.params.id);
  res.render("articles/delete", { article: article, title: "Delete Article" });
}));

/* Delete individual article. */
router.post('/:id/delete', asyncHandler(async (req ,res) => {
  // const article = await Article.findByPk(req.params.id);
  // await article.destroy();
  console.log(req.params.id);
  res.redirect("/articles");
}));

Note that in the router.post section, the console log will print out the correct route parameter id.

That's fine, but now look at the slightly revised code -

/* Delete article form. */
router.get("/:id/delete", asyncHandler(async (req, res) => {
  const article = await Article.findByPk(req.params.id);
  res.render("articles/delete", { article: {}, title: "Delete Article" });
}));

/* Delete individual article. */
router.post('/:id/delete', asyncHandler(async (req ,res) => {
  // const article = await Article.findByPk(req.params.id);
  // await article.destroy();
  console.log(req.params.id);
  res.redirect("/articles");
}));

In the router.post section, the console log should still print out the same route parameter id, all else being equal. However, it prints out as undefined. Somehow, it seems that in the router.get section, the res.render has the object article property set as empty here ... article: {}, and it has an effect. So back to the router.post section- - why would the req.params.id be affected by this, as I thought it was independent, based on the url?