Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 9, 2023 02:46
Show Gist options
  • Save code-boxx/0b6e437e6c303f93b82d67f3b5eb0adc to your computer and use it in GitHub Desktop.
Save code-boxx/0b6e437e6c303f93b82d67f3b5eb0adc to your computer and use it in GitHub Desktop.
NodeJS Express Save HTML Form Into Database

NODEJS EXPRESS SAVE FORM INTO DATABASE

https://code-boxx.com/save-html-form-into-database-nodejs/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Install required modules - npm i sqlite3 express multer
    • Create the dummy database - node 1b-create.js
    • Start the Express server - node 3-server.js.
  2. Access http://localhost/ in your browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE dummy (
id INTEGER,
email TEXT NOT NULL,
txt TEXT NOT NULL,
PRIMARY KEY("id" AUTOINCREMENT)
);
// (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");
}
});
<!DOCTYPE html>
<html>
<head>
<title>Save Form Into Database Demo</title>
<meta charset="utf-8">
<style>
/* (X) NOT IMPORTANT - COSMETICS */
* {
font-family: Arial, Helvetica, sans-serif;
font-size: 1em;
box-sizing: border-box;
}
form {
max-width: 400px;
padding: 20px;
border: 1px solid #eee;
background: #f7f7f7;
}
label, input {
display: block;
width: 100%;
}
label { padding: 10px 0; }
input { padding: 10px; }
input[type=text], input[type=email] { border: 1px solid #d1d1d1; }
input[type=submit] {
margin-top: 20px;
border: 0;
cursor: pointer;
color: #fff;
background: #515fbf;
}
</style>
</head>
<body>
<!-- (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>
<!-- (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>
</body>
</html>
// (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`));
call npm i sqlite3 express multer
node 1b-create.js
node 3-server.js
source "npm i sqlite3 express multer"
node ./1b-create.js
node ./3-server.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment