Save HTML Form Into Database With NodeJS (Simple Example)

Welcome to a beginner’s tutorial on how to save an HTML form into the database in NodeJS. So you have just started with NodeJS, and wondering how to submit and save an HTML form into the database? Well, read on for the example!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Download and unzip into your project folder.
  • Install the required modules – npm install sqlite3 express multer.
  • Run 1b-create.js to create the dummy SQLite database.
  • Run 3-server.js and access http://localhost in the browser.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

SCREENSHOT

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

SAVE HTML FORM INTO DATABASE

All right, let us now get into the details of saving an HTML form into the database in Node JS.

 

PART 1) DUMMY DATABASE

1A) THE SQL

1-server.js
CREATE TABLE dummy (
  id INTEGER,
  email TEXT NOT NULL,
  txt TEXT NOT NULL,
  PRIMARY KEY("id" AUTOINCREMENT)
);

For this example, we will be working with this simple table with only 3 fields:

  • id Primary key, auto-increment.
  • email Email of the user.
  • txt Whatever text or random content.

 

1B) CREATE THE DATABASE FILE

1b-create.js
// (A) REQUIRED MODULES
const fs = require("fs"),
sqlite = require("sqlite3");
 
// (B) CREATE DUMMY DATABASE
const db = new sqlite.Database("dummy.db", err => {
  if (err) { console.log(err); }
  else {
    db.exec(fs.readFileSync("1a-dummy.sql", "utf8"));
    db.close();
    console.log("Database created");
  }
});

Don’t think this one needs a lot of explanation – We are just reading the above SQL file and creating the actual dummy.db.

 

 

PART 2) DUMMY HTML FORM

2A) THE HTML

2-form.html
<!-- (A) HTML FORM -->
<form method="post" id="demo" onsubmit="return goForm()">
  <label>Email</label>
  <input type="email" name="email" required value="jon@doe.com">
  <label>Text</label>
  <input type="text" name="txt" required value="It works!">
  <input type="submit" value="Go!">
</form>

Well, just a “regular Joe HTML form”.

 

2B) THE JAVASCRIPT

2-form.html
<!-- (B) AJAX SUBMIT -->
<script>
function goForm () {
  // (B1) GET HTML FORM
  var data = new FormData(document.getElementById("demo"));
 
  // (B2) AJAX SUBMIT
  fetch("/go", { method:"POST", body:data })
  .then(res => res.text())
  .then(txt => alert(txt))
  .catch(err => console.error(err));
  return false;
}
</script>

For the form submission, we will be using fetch() to send the HTML form via POST to /go.

 

 

PART 3) NODEJS EXPRESS SERVER

3-server.js
// (A) LOAD MODULES
const path = require("path"),
      multer = require("multer"),
      bodyParser = require("body-parser"),
      express = require("express"),
      sqlite = require("sqlite3");
 
// (B) EXPRESS SERVER & MIDDLEWARE
const app = express();
app.use(multer().array());
app.use(bodyParser.urlencoded({ extended: false }));
 
// (C) SERVE DUMMY HTML FORM
app.get("/", (req, res) => res.sendFile(path.join(__dirname, "/2-form.html")));
 
// (D) PROCESS SUBMITTED FORM
app.post("/go", (req, res) => {
  // (D1) SAVE INTO DATABASE
  let db = new sqlite.Database("dummy.db");
  db.run(`INSERT INTO dummy (email, txt) VALUES (?,?)`, [
  req.body.email, req.body.txt
  ], function (err) {
    if (err) { console.log(err); }
    else { console.log(`INSERTED - ID ${this.lastID}`); }
  });
  db.close();
 
  // (D2) RESPOND
  res.status(200);
  res.send("OK");
});
 
// (E) START!
app.listen(80, () => console.log(`Server running at port 80`));

Finally, we will build an HTTP server with Express.

  1. Load the necessary modules…
  2. Create the Express HTTP server, use multer and body-parser to properly “decode” the POST.
  3. Serve 2-form.html at /.
  4. When the form is submitted to /go, this section will INSERTit into the database.
  5. Captain Obvious to the rescue – Start the HTTP server.

The end.

 

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

SMALL NOTES ON SQLITE

Horray, this example works. With SQLite, there’s no need to download and install “crazy database stuff”. But take note – SQLite is a great tool for learning, but it is bad in terms of performance. So please pick up a database in your own free time, it does not take that long – MYSQL, POSTGRESQL, MSSQL, MongoDB, etc…

 

COMPATIBILITY CHECKS

This example works on all modern browsers.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *