Sending parameters in POST request from react to node JS

Viewed 15

I am trying to send a singular string to my backend to use as the message in an email. I think I'm sending the information correctly but I've tried many variations of getting the value that I'm sending, but it always comes back undefined or throws an internal server error

Here's the function call and POST request

function Email(){
  console.log("CLICKED")
  var data = [
    {
      message: "This is the message I want in my email"
    }
  ]

  fetch('http://localhost:8000/email',{
    method: 'POST',
    headers: { "Content-Type": "application/json"},
    body: JSON.stringify(data)
  }).then(()=>{
    console.log("Email sent")
  })

Here's the backend post

app.post("/email", function(req, res){
  console.log("req" + req.body.message)
  const message = {
    from: "email@gmail.com",
    to: "email@gmail.com",
    subject: "Hello " + req.body.message,
    text: req.body.message
  }
  
  transport.sendMail(message, (err, info) => {
  if (err) {
  console.log(err)
    res.send("Email not sent")
  } else {
    res.send("Email sent")
  }
  });
})

In the subject, it will send Hello just fine but the body will return as undefined. If I change things too much I will get a type error.

TypeError: Cannot read properties of undefined (reading 'message')
0 Answers
Related