Node.js is one of the famous open-source environments that allows to you run javascript scripts outside the browser. MERN and MEAN stacks are the two most popular combination that helps you to create an amazing application. In this article, we will be creating a simple beginner-friendly Contact Form App with Node, Bootstrap, and MongoDB. Before starting the project we have to make sure that Node.js and MongoDB are installed in your system.
Project Structure:
Step 1: Create a project folder and open that folder in your IDE.
First to create a package.json file with values that you supply, use the npm init command in the terminal of IDE.
npm init
You can customize the questions asked and fields created during the init process or leave it as default. After the process, you will find the package.json file in your project folder.
Step 2: Next create an index.js file in the project folder, which will be the entry point of the app.
Step 3: Now install the dependencies express, mongoose, and nodemon using the npm command.
npm install express mongoose nodemon
Installing express, mongoose, and nodemon
It will take some time to install the dependencies and after it’s done, a folder named node_modules will be created in the package.json file under dependencies, you will find the name of all the installed dependencies along with their version.
Dependencies
Step 4: We will next open the index.js file and create a simple express app with the following code.
Javascript
const express = require( "express" );
const mongoose = require( "mongoose" );
const port = 80;
const app = express();
app.get( "/" , (req, res) => {
res.send( "Hello World" );
});
app.listen(port, () => {
console.log(`The application started
successfully on port ${port}`);
});
|
This code creates a simple express app that starts a server and listens on port 80 for connections. The app responds with “Hello World” for requests to “/”.
Step 5: To run the code, go to the terminal and type
nodemon index.js
Application started successfully
Step 6: Then open your browser, use http://localhost, or simply localhost to access the server from itself.
Localhost
The page shows “Hello World”, which means our express app is working properly.
Step 7: We now need to add 2 lines of code, as we will need express.json() and express.urlencoded() for POST and PUT requests. Express provides us with middleware to deal with incoming data objects in the body of the request. In both POST and PUT requests, we are sending data objects to the server and are asking the server to accept or store that data object, which is enclosed in the req.body of that request.
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
Step 8: Create a folder named public inside the project folder. We will create all the static HTML files in the public directory of our project.
// For serving static html files
app.use(express.static('public'));
Step 9: Now we are going to connect to the mongoose database by using the following code. The name of the database for this project is given as projectDG
mongoose.connect("mongodb://localhost/projectDG", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let db = mongoose.connection;
Step 10: Next, we are going to define a post method to save the data of the contact form to our database. We define our data object and create a collection named users here. On successful data insertion, we will redirect to formSubmitted.html
This is the main part of the index.js file where the post request will be handled and proper transfer of the data will be taken place from the client request to the main database server.
app.post("/formFillUp", (req, res) => {
const name = req.body.name;
const reason = req.body.reason;
const email = req.body.email;
const phone = req.body.phone;
const city = req.body.city;
const state = req.body.state;
const addressline = req.body.addressline;
const data = {
name: name,
reason: reason,
email: email,
phone: phone,
city: city,
state: state,
addressline: addressline,
};
db.collection("users").insertOne(data,
(err, collection) => {
if (err) {
throw err;
}
console.log("Data inserted successfully!");
});
return res.redirect("formSubmitted.html");
});
Final index.js will look like as below:
Filename: index.js
Javascript
const express = require( "express" );
const mongoose = require( "mongoose" );
const port = 80;
const app = express();
useNewUrlParser: true ,
useUnifiedTopology: true ,
});
let db = mongoose.connection;
app.use(express.json());
app.use(express.static( "public" ));
app.use(express.urlencoded({ extended: true }));
app.get( "/" , (req, res) => {
res.set({
"Allow-access-Allow-Origin" : "*" ,
});
return res.redirect( "index.html" );
});
app.post( "/formFillUp" , (req, res) => {
const name = req.body.name;
const reason = req.body.reason;
const email = req.body.email;
const phone = req.body.phone;
const city = req.body.city;
const state = req.body.state;
const addressline = req.body.addressline;
const data = {
name: name,
reason: reason,
email: email,
phone: phone,
city: city,
state: state,
addressline: addressline,
};
db.collection( "users" ).insertOne(
data, (err, collection) => {
if (err) {
throw err;
}
console.log( "Data inserted successfully!" );
});
return res.redirect( "formSubmitted.html" );
});
app.listen(port, () => {
console.log(`The application started
successfully on port ${port}`);
});
|
Step 11: Now we will create index.html, formSubmittedhtml, and style.css files inside the public folder.
index.html:
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "utf-8" />
< meta name = "viewport" content=" width = device -width,
initial-scale = 1 , shrink-to-fit = no " />
< link rel = "stylesheet" href =
integrity =
"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin = "anonymous" />
< link rel = "stylesheet" href = "./style.css" />
< link href =
rel = "stylesheet" />
</ head >
< body >
< div class = "container mt-3" >
< br />
< h1 >Contact Us</ h1 >
< br />
< form action = "/formFillUp" method = "POST" >
< div class = "form-row" >
< div class = "form-group col-md-6" >
< label for = "inputName"
style = "font-size: 23px" >
Name
</ label >
< input type = "text" class = "form-control"
id = "name" name = "name" />
</ div >
< div class = "form-group col-md-6" >
< label for = "inputReason"
style = "font-size: 23px" >
Reason for contacting
</ label >
< input type = "text" class = "form-control"
id = "reason" name = "reason" />
</ div >
</ div >
< div class = "form-row" >
< div class = "form-group col-md-6" >
< label for = "inputEmail"
style = "font-size: 23px" >
Email
</ label >
< input type = "email" class = "form-control"
id = "inputEmail" name = "email" />
</ div >
< div class = "form-group col-md-6" >
< label for = "inputPhone"
style = "font-size: 23px" >Phone
</ label >
< input type = "text" class = "form-control"
id = "inputPhone" name = "phone" />
</ div >
</ div >
< div class = "form-row" >
< div class = "form-group col-md-6" >
< label for = "inputCity"
style = "font-size: 23px" >City
</ label >
< input type = "text" class = "form-control"
id = "inputCity" name = "city" />
</ div >
< div class = "form-group col-md-6" >
< label for = "inputState"
style = "font-size: 23px" >State
</ label >
< input type = "text" class = "form-control"
id = "inputState" name = "state" />
</ div >
</ div >
< div class = "form-group" >
< label for = "inputAddress"
style = "font-size: 23px" >Address</ label >
< input type = "text" class = "form-control"
id = "inputAddress" name = "addressline" />
</ div >
< button type = "submit" class = "btn btn-primary" >
Submit
</ button >
</ form >
</ div >
</ body >
</ html >
|
Output:
index.html
formSubmitted.html
HTML
<!DOCTYPE html>
< html >
< head >
< title >Form Submitted Successfully</ title >
< link rel = "stylesheet" href = "./style.css" />
< link href =
rel = "stylesheet" />
</ head >
< body >
< div class = "containerFormSubmittedMessage" >
< h1 >Form Submitted Successfully!</ h1 >
< p >
Thank you for contacting us! Our
team will mail you shortly.
</ p >
</ div >
</ body >
</ html >
|
Output:
formSubmitted.html
style.css
CSS
body {
background-image : linear-gradient( 120 deg,
#9de7fa 0% ,
#f89fba 100% );
color : white ;
font-family : "Poppins" , sans-serif ;
min-height : 100 vh;
}
.btn-primary {
color : #fff ;
background-color : #f89fba ;
border-color : #f89fba ;
}
.containerFormSubmittedMessage {
display : flex;
flex- direction : column;
margin : auto ;
justify- content : center ;
align-items: center ;
height : 200px ;
border : 3px solid whitesmoke;
}
|
Step 12: After creating these three files, we are almost done with our project. We will now start MongoDB. Open the Windows Powershell window and then type the command mongod.
mongod
Type mongod command in powershell window
Open another Windows Powershell window and type the command mongo
mongo
Type mongo command in another powershell window
Step 13: Open your IDE, and in the terminal type nodemon index.js to start the app. Go to localhost.
Note: Data inserted successfully will be printed after handling the post request properly.
- Fill up the details of the contact form. On successful submission of the form, you will be redirected to formSubmitted.html from index.html.
Contact Form
- Now to check if our data entered in the contact form has been saved to the projectDG database, we will use the following commands in the second Windows Powershell window.
This command lists all the databases in MongoDB:
show dbs
This command will let us switch to our database:
use projectDG
This command we will check of a particular data in the collection:
db.users.find()
Data present in users collection in projectDG database
We can see clearly out data has been inserted into the MongoDB database.
Last Updated :
31 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...