title: Why does req.body return null when I was use event.preventDefault() with fetch api, express, and node.js?
body: <p>I want to submit a form and then return an object from my MongoDB database without reloading the page. Therefore when I submit my form I use an event handler that prevents the default behavior of the form to reload the page. The problem is this is interfering with my server side script and causing <code>req.body</code> to return null. If I remove <code>e.preventDefault()</code> from my client side script then <code>req.body</code> works fine but the page refreshes and just displays a json from my database. How would I get around this?</p>
  
  <p>Here is my HTML:</p>
  
  <pre><code>    &lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
      &lt;head&gt;
          &lt;meta charset="utf-8"&gt;
          &lt;meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"&gt;
          &lt;title&gt;Message in a Bottle&lt;/title&gt;
          &lt;link href="https://fonts.googleapis.com/css?family=Roboto+Slab&amp;display=swap" rel="stylesheet"&gt;
          &lt;link rel="stylesheet" type="text/css" href="styles.css"&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;div id = "icon"&gt;
              &lt;img id = "iconImg" style = "width:100%"src = "icon.svg"/&gt;
          &lt;/div&gt;
          &lt;div id = "form"&gt;
              &lt;form method="post" action="/"&gt;
                  &lt;input type="text" name="sender"/&gt;
                  &lt;textarea rows="20" cols="50" name="message"&gt;&lt;/textarea&gt;
                  &lt;button type = "submit" onclick="onClick(event)"&gt;submit&lt;/button&gt;
              &lt;/form&gt;
          &lt;/div&gt;
          &lt;div id = "message"&gt;
              &lt;p id = "senderName"&gt;&lt;/p&gt;
              &lt;p id = "response"&gt;&lt;/p&gt;
              &lt;button onclick="closeMessage()"&gt;New Message&lt;/button&gt;
          &lt;/div&gt;
      &lt;/body&gt;
      &lt;script type = "text/javascript" src = "packageHandler.js"&gt;&lt;/script&gt;
  
  &lt;/html&gt;
  </code></pre>
  
  <p>Here is my client side script:</p>
  
  <pre><code>const form = document.getElementById("form");
  const icon = document.getElementById("icon");
  const message = document.getElementById("message");
  
  
  function onClick(e){
      e.preventDefault();
      console.log("loading results");
      form.style.opacity = "0%";
      form.style.pointerEvents = "none";
      icon.style.width = "80%";
      fetch('http://localhost:3000/', {method: 'POST'})
          .then((response) =&gt; {
          icon.style.width = "33%";
          message.style.opacity = "100%";
          message.style.pointerEvents = "auto";
          return response.json();
      })
          .then((data) =&gt; {
          document.getElementById("senderName").innerHTML = data.name;
          document.getElementById("response").innerHTML = data.message;
      });
      //await results
      //fade in &lt;div id = "message"&gt;
      //display results in &lt;div id = "message"&gt;
  }
  function closeMessage(){
      console.log("message closed")
      form.style.opacity = "100%";
      form.style.pointerEvents = "auto";
      message.style.opacity = "0%";
      message.style.pointerEvents = "none";
      //fade out &lt;div id = "message"&gt;
      //fade in &lt;div id = "form"
  }
  </code></pre>
  
  <p>Here is my server side script:</p>
  
  <pre><code>const express = require('express');
  const MongoClient = require('mongodb').MongoClient;
  require('dotenv/config');
  const app = express();
  const fs = require('fs');
  
  const port = 3000;
  
  app.use(express.urlencoded());
  app.use(express.static('public'));
  
  
  app.listen(port, () =&gt; console.log(`Example app listening on port ${port}!`));
  
  //Routes
  app.get('/', (req, res) =&gt; {
    fs.readFile('./views/home.html', function (err, data) {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.write(data);
      res.end();
    });
  });
  
  app.post('/', (req, res) =&gt; {
    MongoClient.connect(process.env.DB_CONNECTION, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
      if (err) throw err;
      const dbo = db.db("mydb");
      const messageTable = dbo.collection("messages");
      let myobj = 
      [{ 
        name: req.body.sender,
        message: req.body.message
      }];
      console.log(myobj)
      messageTable.insertMany(myobj, function (err, res) {
        if (err) throw err;
        console.log("1 document inserted");
      });
      var myPromise = () =&gt; {
        return new Promise((resolve, reject) =&gt; {
          messageTable.aggregate(
            [{ $sample: { size: 1 } }]
          ).toArray((err, data) =&gt; {
            err
              ? reject(err)
              : resolve(data[0]);
          });
        });
      }
      //Step 2: async promise handler
      var callMyPromise = async () =&gt; {
        var result = await (myPromise());
        //anything here is executed after result is resolved
        return result;
      };
  
      //Step 3: make the call
      callMyPromise().then(function (result) {
        db.close();
        res.json(result)
        });
  
      });
  
  
    });  //end mongo client
  </code></pre>