Home > Software design >  Routing for Posts and Comments with Node/Express not working
Routing for Posts and Comments with Node/Express not working

Time:11-02

I'm working on a Crud project (with auth, posts and comments) and I'm having a little trouble understanding how to do my routing efficiently and link Posts with Comments.

This is my routing for Comments:


router.post("/:id", auth, comCtrl.createComment);
router.post("/:id", auth, comCtrl.getPostComments);
router.post("/:id", auth, comCtrl.deleteComment);

And the App.js:

app.use("/api", postRoutes);
app.use("/api/comments", comRoutes);

And the Comment Controller in order to get All Comments for a Post:

exports.getPostComments = async (req, res) => {
  const { PostId } = req.params.id;

  Comment.findAll({
    where: {
      PostId: PostId,
    },
    order: [["createdAt", "DESC"]],
    include: [
      {
        model: User,
        attributes: ["id", "firstName", "lastName", "imageUrl"],
      },
    ],
    order: [["createdAt", "ASC"]],
  })
    .then((comment) => {
      res.status(200).send(comment);
    })
    .catch((err) =>
      res.status(500).send({
        err,
      })
    );
}; 

A creation of a new comment is working in Postman (for example I have a Post with an id 28 and by making a post request on "http://localhost:8000/api/comments/28", the comment is created and indeed related to Post), but making a GET request with the same URL in order to get all comments from this Post, I get an error 404.

What have I done wrong?

The controller looks fine, but from what I found, putting "/:id" everywhere in my routes is a bad practice, but event when I change it for "/:PostId" for example, it does nothing.

CodePudding user response:

router.post("/:id", auth, comCtrl.createComment);
router.post("/:id", auth, comCtrl.getPostComments);
router.post("/:id", auth, comCtrl.deleteComment);

router.post registers a handler for POST requests.

When you get an HTTP POST request for /api/comments/28 it gets handled by comCtrl.createComment.

If comCtrl.createComment then calls next (the third argument) — although I'm assuming it doesn't since you aren't trying to write middleware — then it gets passed along the list of handlers to the next match (comCtrl.getPostComments).

When you get an HTTP GET request for /api/comments/28 you have no handlers because you haven't called router.get(), so you get a 404 error. (this should be a 405 error, but chalk that up to an Express design decision I disagree with).

If you want to handle GET requests then you need to write code that says what to do when a GET request is received.

  • Related