0

req.body.message is returning undefined when printing. Form is trying to make a post request.

//Form
 <form  id="messagesubmission"method="post"  action="/postmessage">
     <label for="message">message:</label>
    <input type="text" name="message" /><br />
    <input type="submit"/>
</form>

//Javascript code to intercept data
 document.getElementById('messagesubmission').addEventListener('submit', function (event) {
    event.preventDefault(); // Prevent the default form submission
    console.log("hit");
    // Get the form data
    var MessageData = new FormData(this);

    // Send the form data to the server using Fetch API
    fetch('/postmessage', {
      method: 'POST',
      body: MessageData
    })
      .then(function (data) {
        // Update the result container with the received data
        console.log(data);
      })
      .catch(function (error) {
        console.error('Error:', error);
      });
  });

//Express Data
app.post("/postmessage", (req, res) => {
   const MessageData =  storedUsername + " - " + req.body.message  + "\n"; 
  console.log(MessageData);
  res.setHeader('Content-Type', 'application/json');
  fs.appendFileSync('messagelist.txt', MessageData, { flag: 'a' });
  res.send(JSON.stringify({ variable: MessageData}));
});

I did some basic trouble shooting and console logging. But it keeps returning undefined

  • 1
    This question is asked a lot on Stackoverflow. [Express.js req.body undefined](https://stackoverflow.com/questions/9177049/express-js-req-body-undefined). And [another recent duplicate](https://stackoverflow.com/questions/76378677/node-js-hapi-cant-show-the-caught-value#comment134682844_76378677). – Andy Ray Jun 06 '23 at 02:34
  • Your code shows the same mistake twice. First, `fetch()` does NOT read the response of the request by default. So `fetch(...).then(data => console.log(data))` will show you a response object, NOT the data from the `fetch()` response. To get that data, you need `response.json().then()`. Second, Express does not automatically read the body of incoming requests so `req.body` is empty by default. Instead you need express middleware that matches the content-type of your data and that middleware will read the body of the request and populate `req.body` for you. – jfriend00 Jun 06 '23 at 04:31
  • 1
    Probably, you need `app.use(express.urlencoded())` to read the urlencoded `FormData` and then populate `req.body`. – jfriend00 Jun 06 '23 at 04:32

0 Answers0