ROhan Gandhi
ROhan Gandhi

Reputation: 11

Not able to pass data from HTTP post request to the javascript(expressjs) controller

I am using react at the frontend and expressjs at the backend. Creating a simple post request and passing json data to the back end via the front end. THe request consist of body{title:"some title", content:"some content"}. In the back end if I console.log(req.body), I am getting an empty object. Also If i use postman it works correctly. Front end Code :

fetch(url, {
      method: method,
      header: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: postData.title,
        content: postData.content
      })
    })

BackEnd code:

const title = req.body.title;
  const content = req.body.content;
  console.log(req);
  res.status(201).json({
    message: 'created nicely',
    post: {
      _id: '78',
      title: title,
      content: content,
      creator: { name: 'mera naam' },
      createdAt: new Date()
    }
  });

Upvotes: 1

Views: 236

Answers (1)

cbr
cbr

Reputation: 13652

The header property should be headers.

fetch(url, {
  method: method,
  headers: {
  //  ^^^
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    title: postData.title,
    content: postData.content,
  }),
})

Because the Content-Type header isn't being sent due to the misspelling, body-parser or express.json() (whichever you're using) doesn't parse the request body.

Upvotes: 3

Related Questions