Read HTML Form Data Using GET and POST Method in Node.js
How to create a server application using Node.js that will read data from HTML form and will perform basic operations like insert, read, update and delete on SQLite3 database using GET and POST requests. We’ll also add security features by using modules like Helmet and Express-rate-limit.
Prerequisites –
Knowledge of — HTML, CSS, Node.js, and SQLite3
Node.js and SQLite3 should be installed on your local machine.
So, now we are ready to initiate our project. let’s dive in.
Step 1: First of all, open the terminal and create one directory which will be dedicated for our project. Navigate into that directory and run npm init . Then you will be asked to enter various details about your application, which will be stored as a json file named ‘Package.json’. Then you have to run following commands —
npm install express --save to install the ‘express’ module, npm install sqlite3 --save to install ‘sqlite3’ module, and npm install body-parser --save to install ‘body-parser’ module npm install helmet --save to install ‘helmet’ module. npm install express-rate-limit --save to install ‘express-rate-limit’ module.
Note- helmet is a Node.js module that helps in securing ‘express’ applications by setting various HTTP headers. It helps in mitigating cross-site scripting attacks, misissued SSL certificates etc.
Express-rate-limit module is a middleware for Express which is used to limit repeated requests to public APIs and/or endpoints such as password reset. By limiting the number of requests to the server, we can prevent the Denial-of-Service (DoS) attack. It is the type of attack in which the server is flooded with repeated requests making it unavailable to its intended users and ultimately shutting it down.
{
"name": "crudapp_htmlform",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/souvik-pl/crudApp_htmlForm.git"
},
"author": "Souvik",
"license": "ISC",
"bugs": {
"url": "https://github.com/souvik-pl/crudApp_htmlForm/issues"
},
"homepage": "https://github.com/souvik-pl/crudApp_htmlForm#readme",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"express-rate-limit": "^5.1.3",
"helmet": "^4.1.1",
"sqlite3": "^5.0.0"
}
}
Step 2: Now let’s start writing HTML and CSS code. We will keep our HTML and CSS files in a directory named ‘public’, which is itself present in our project directory. In the HTML file, we’ll define the head section first.
/public/form.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<link rel = "stylesheet" href="style.css">
<title> My Form </title>
</head>
<body>
<header>
<h1>Employee Database</h1>
</header>
<form action="/add" method="POST">
<fieldset>
<h3>Add new employee</h3>
<label>Employee ID</label>
<input type ="text" id = 'empID' name="id" placeholder="1,2,3..." required>
<br><br>
<label>Name</label>
<input type="text" id = "name" name="name" placeholder="Tom Cruise" required>
<br><br>
<button type ="reset">Reset</button>
<button type ="submit">Submit</button>
</fieldset>
</form>
<form action="/view" method="POST">
<fieldset>
<h3>View an employee</h3>
<label>Employee ID</label>
<input type="text" id="empID" name="id" placeholder="1,2,3..." required>
<br><br>
<button type ="reset">Reset</button>
<button type ="submit">Submit</button>
<br><br><br>
</fieldset>
</form>
<form action="/update" method="POST">
<fieldset>
<h3>Update an employee</h3>
<label>Employee ID</label>
<input type ="text" id = 'empID' name="id" placeholder="1,2,3..." required>
<br><br>
<label>New Name</label>
<input type="text" id = "name" name="name" placeholder="Maverick" required>
<br><br>
<button type ="reset">Reset</button>
<button type ="submit">Submit</button>
</fieldset>
</form>
<form action="/delete" method="POST">
<fieldset>
<h3>Delete an employee</h3>
<label>Employee ID</label>
<input type ="text" id = 'empID' name="id" placeholder="1,2,3..." required>
<br><br>
<button type ="reset">Reset</button>
<button type ="submit">Submit</button>
<br><br><br>
</fieldset>
</form>
<footer>
<hr>
<h4>Please enter 'http://localhost:3000/close' to close the database connection before closing this window</h4>
</footer>
</body>
</html>
Step 3: Now we’ll write the CSS codes for styling our webpage.
body{
background-color: #cce6ff;
}
header{
text-align: center;
height: 100px;
padding-top: 1px;
background-color: #3399ff;
color: #FFFFFF;
font-size: x-large;
}
h3{
margin-top: 2px;
text-align: center;
background-color: #80bfff;
}
form{
width: 45%;
display: inline-block;
margin: 20px;
}
footer{
margin-top: 3%;
text-align: center;
}
Step 4: Since, we have designed our front end, now we’ll build our back-end server application in Node.js. We’ll create a file called ‘app.js’ in our main project directory and import all the necessary modules.
app.js
var sqlite3 = require('sqlite3').verbose();
var express = require('express');
var http = require('http');
var path = require("path");
var bodyParser = require('body-parser');
var helmet = require('helmet');
var rateLimit = require("express-rate-limit");
var app = express();
var server = http.createServer(app);
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
var db = new sqlite3.Database('./database/employees.db');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'./public')));
app.use(helmet());
//app.use(limiter);
db.run('CREATE TABLE IF NOT EXISTS emp(id TEXT, name TEXT)');
app.get('/', function(req,res){
res.sendFile(path.join(__dirname,'./public/form.html'));
});
// Add
app.post('/add', function(req,res){
db.serialize(()=>{
db.run('INSERT INTO emp(id,name) VALUES(?,?)', [req.body.id, req.body.name], function(err) {
if (err) {
return console.log(err.message);
}
console.log("New employee has been added");
res.send("New employee has been added into the database with ID = "+req.body.id+ " and Name = "+req.body.name);
});
});
});
// View
app.post('/view', function(req,res){
db.serialize(()=>{
db.each('SELECT id ID, name NAME FROM emp WHERE id =?', [req.body.id], function(err,row){ //db.each() is only one which is funtioning while reading data from the DB
if(err){
res.send("Error encountered while displaying");
return console.error(err.message);
}
res.send(` ID: ${row.ID}, Name: ${row.NAME}`);
console.log("Entry displayed successfully");
});
});
});
//Update
app.post('/update', function(req,res){
db.serialize(()=>{
db.run('UPDATE emp SET name = ? WHERE id = ?', [req.body.name,req.body.id], function(err){
if(err){
res.send("Error encountered while updating");
return console.error(err.message);
}
res.send("Entry updated successfully");
console.log("Entry updated successfully");
});
});
});
// Delete
app.post('/delete', function(req,res){
db.serialize(()=>{
db.run('DELETE FROM emp WHERE id = ?', req.body.id, function(err) {
if (err) {
res.send("Error encountered while deleting");
return console.error(err.message);
}
res.send("Entry deleted");
console.log("Entry deleted");
});
});
});
// Closing the database connection.
app.get('/close', function(req,res){
db.close((err) => {
if (err) {
res.send('There is some error in closing the database');
return console.error(err.message);
}
console.log('Closing the database connection.');
res.send('Database connection successfully closed');
});
});
server.listen(3000, function(){
console.log("server is listening on port: 3000");
});
In the above code, we have created an instance of express, named ‘app’ and we have also created a database named ‘employee’ in the ‘database’ directory which is present in our current directory.
windowMs is the timeframe for which requests are checked/remembered.
max is the maximum number of connections during windowMs milliseconds before sending a 429 response.
bodyParser.urlencoded() returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option.
express.static() is used to serve static files in ‘express’.
Then, we’ll create a table named ‘emp’ in the database having two columns- ‘id’ and ‘name’ using the following code –
db.run(‘CREATE TABLE IF NOT EXISTS emp(id TEXT, name TEXT)’);
The above code will make sure that ‘emp’ table won’t be created again and again whenever we run the application.
Step 7: Then, open the Network tab by clicking on Inspect Element. Click on localhost and you will notice some additional set of headers in the response, which are set by the helmet module.
Readme :
# Reading HTML form data using GET and POST method in Node.js
It is a server application developed using Node.js that will read data from HTML form and will perform basic operations like insert, read, update and delete on SQLite3 database using GET and POST requests.
Some security features are also added by using modules like Helmet and Express-rate-limit.
Reference
https://medium.com/swlh/read-html-form-data-using-get-and-post-method-in-node-js-8d2c7880adbf
https://inloop.github.io/sqlite-viewer/
https://github.com/souvik-pl/crudApp_htmlForm\
JavaScript in Plain English – Souvik Paul
https://souvikpl.medium.com/
How to handle the POST request body in Node.js without using a framework
Server Side Rendering Html Page in Nodejs
Node.js Express Examples: Rendered, REST, and Static Websites