0

I am getting the following error when trying to handle post requests:

TypeError: Cannot read property 'forEach' of undefined

Please let me know what I am doing wrong. This is my code:

router.post("/", validateToken, async (req, res) => {
    const { post, newTags } = req.body;
    console.log("my body!", req.body);
    
    post.fullName = req.user.fullName;
    post.UserId = req.user.id;
    await Posts.create(post);
      
    newTags.forEach((tag) => {
        tagPost(tag, id);
    });
    
    res.json(post);
});

Thanks.

6
  • 2
    Please show result of console.log("my body!", req.body); Commented Aug 2, 2021 at 11:15
  • Do you have any bodyparsing middleware? If yes are you sure your body does in fact have a newTags property? Seems it doesn't. Commented Aug 2, 2021 at 11:17
  • Does this answer your question? Express.js req.body undefined Commented Aug 2, 2021 at 11:22
  • Yeah her it is........... my body! { postText: 'Another data type is the Boolean. Booleans may only be one of two values: true or false. They are basically little on-off switches, where true is on and false is off. These two states are mutually exclusive. c\n' + '\n', postTitle: 'In HTML and css' } Commented Aug 2, 2021 at 11:45
  • there is no newTags property in the body you posted in the comment. Only postText and postTitle ... So obviously newTags will be undefined after deconstructing the body ... Which makes me wonder why post.fullName doesn't throw an error, because post will also be undefined Commented Aug 2, 2021 at 12:42

2 Answers 2

1

If you are using Content-Type: application/json to POST data, make sure to add parser middleware. You can use body-parser in your API router by installing it with npm install body-parser and implementing it with lines bellow:

const body-pareser = require('body-parser');
// your router init, etc...
router.use(body-parser.json());
// your routes, middlewares, whatever
Sign up to request clarification or add additional context in comments.

Comments

0

As per documentation, req.body is undefined by default. You have to implement a body-parsing middleware to have it populated.

This is a very similar question (if not identical). Please make some research before asking.

2 Comments

if body was undefined, an error would be thrown already at const { post, newTags } = req.body; because you cannot deconstruct an undefined. It's more likely, that there is a body (and it's also parsed), but it doesn't contain a newTags property`
@derpirscher you are right, didn't notice the deconstruction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.