'POST request on /post/:id/comment works, although i get an Cannot GET error

i have this router.post:

router.post("/:id/comment", async (req, res) => {
  // find out which post you are commenting
  const id = req.params.id;
  // get the comment text and record post id
  const comment = new Comment({
    author: req.body.author,
    text: req.body.text,
    post: id,
  });
  // save comment
  await comment.save();
  // get this particular post
  const postRelated = await Post.findById(id);
  // push the comment into the post.comments array
  postRelated.comments.push(comment);
  // save and redirect...
  await postRelated.save(function (err) {
    if (err) {
      console.log(err);
    }
    res.redirect("/");
  });
});

It works, and it adds the comment to the comments array of post, although in Postman i get an error: Cannot GET. I do not really understand why and I rather not have any errors in my app, although the post request works.

ADDITIONAL INFO The Post model:

const { Schema, model } = require("mongoose");

const postSchema = new Schema({
  photoUrl: {
    type: String,
    required: true,
  },
  description: String,
  likes: Number,
  creationDate: Date,
  author: String,
  comments: [
    {
      type: Schema.Types.ObjectId,
      ref: "Comment",
    },
  ],
});

module.exports = model("Post", postSchema);

The comment model:

const { Schema, model } = require("mongoose");

const commentSchema = new Schema({
  text: {
    type: String,
    required: true,
  },
  creationDate: Date,
  post: { type: Schema.Types.ObjectId, ref: "Post" },
  author: String,
});

module.exports = model("Comment", commentSchema);


Solution 1:[1]

You seem to only be creating a controller for the HTTP method POST if you would want to accept GET requests as well you should create a new controller and replace: router.post with router.get.

Caveat

Keep in mind that GET requests do not accept request bodies.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fabio Nettis