loading...
Cover image for POST to Database Without Routing to a New Page
Vets Who Code

POST to Database Without Routing to a New Page

nbhankes profile image Nathan B Hankes ・1 min read

The vast majority of online Express app tutorials show how to POST data to the database, but they often route to a new page once the data is submitted. This is not always necessary or desirable.

In the example below, I use the 204 No Content HTTP response code in my Express app.post function in order to send data to the database without changing or reloading the webpage. The MDN 204 No Content documentation states:
"The HTTP 204 No Content success status response code indicates that the request has succeeded, but that the client doesn't need to go away from its current page."

In the example code below, the HTML form takes in two numbers, "num" and "numExp". Once the client submits the form data, these number values are formatted in the mongoose schema and passed into the app.post function before it is stored in the database. Nothing changes on the client browser during this process. And sometimes, that's what you want.

var fooSchema = new mongoose.Schema({
  num: Number,
  numExp: Number,
});


var fooBar = mongoose.model("fooBar", fooSchema);


app.post("/new", (req, res) => {
  var myData = new fooBar(req.body);
  myData
    .save()
    .then((item) => {
      res.status(204).send();
    })
    .catch((err) => {
      res.status(400).send("unable to save to database");
    });
});

Your HTML form should contain the following information:

 <form method="post" action="/new" id="cFactorForm" class="form">

For more information on HTTP response codes, visit the HTTP Status Codes reference by runscope.

Discussion

pic
Editor guide