Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Update and Delete Entries

JASON LEE
JASON LEE
15,783 Points

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?