How to make a form using node js and Express
Hello everyone In this article today we are going to cover some basics of the nodeJS forms.
Data forms part of our day to day business.
The data can be collected manually by use of normal hard copy forms or electronically by use of online forms whereby a user fills in the required details
The submitted details are stored securely in a database.
Lets begin
Prerequisites
- NodeJS
- MongoDb
Set Up
In our step number one in the nodeJS forms lets set up our database.
Follow this guide to jump start off with mongoDB
Once you are done lets get to the next step whereby we are going to make a directory name it NodeJSform, this is going to be the name of our project.
using the command line type the following after navigation to your suitable directory
mkdir NodeJSform
In the same directory lets initialize our node project by typing
npm init -y
open the project using your suitable text editor
A package.json file will be generated containing the following
{
"name": "NodeJSform",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Modules Set Up
Lets now install some dependencies that we are going to use in our project
1) Express – NodeJS framework that provide server-side logic
npm i express
2)Mongoose – is an Object Data Modeling (ODM) library for MongoDB and Node
npm i mongoose
3)Body-Parser – since we are going to use a post in order to post data we have to use body-parser
npm i body parser
4)Ejs – EJS is a templating engine used by Node. js. The template engine helps to create an HTML template with minimal code
npm i ejs
5)Nodemone – is a utility that will monitor for any changes in your source and automatically restart your server
npm i nodemone
On our root directory lets make a server.js file, then lets create our server, Our app is going to run on port 3000, add the following codes
const express = require('express')
const app = express()
const port = 3000;
app.listen(port, ()=> console.log(`listening on ${port}`))
then in the package.json file chage it to look like this
{
"name": "NodeJSform",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1",
"mongoose": "^5.12.14",
"nodemon": "^2.0.7"
}
}
to start your server type the following on the command line
npm start
Upon succesful completion the following messages will be displayed on the terminal / command line , listening on 3000
so we wont be refreshing every time we make a change on our code since nodemon has everything for us The next step is to connect our database.
To connect lets create a db.js file on our root folder and then add the following code
DataBase set up
const mongoose = require("mongoose");
mongoose.connect(
"mongodb+srv://ian_test:<password>@ian.qfm7u.mongodb.net/Fistdatabase?retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true,useCreateIndex: true }
)
.then(console.log('connected succesfully'))
.catch(err=> console.log(err))
Make sure you change your password and the First database to your correct default values used while setting up mongodb in the cloud from the article above then lets import it in our server.js file and see what happens at the console type the following
require('./db.js')
upon success the console should display the messages below
connected succesfully
listening on 3000
Models
Now lets define our models,this is a definition of how our data is going to look like in other words the type and the fields we are going to have.
In this form we are going to have the name,email and number fields only Create a file called student.js then add the following codes
const mongoose = require('mongoose')
const studentSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
number:{
type: String,
required: true
}
})
module.exports = mongoose.model('Student' , studentSchema)
Let import our model in our server.js file by adding the codes below
const Student = require('./Student')
Front end part
Now lets get the the front end part create a folder named views
Then create two files one success.ejs and home.ejs
we are going to use bootstrap so lets add the following lines on html codes to our home.js
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>NODEJS FORMS</title>
</head>
<body>
<form>
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" name="name" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Contact</label>
<input type="text" name="contact" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter contact">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</body>
</html>
To display the home.ejs file lets set it in our server.ejs file then define the route, by default we are going to use our default route thats is ‘/’
add the codes below to your server.js file
app.set("view engine" , "ejs")
app.get('/', (req,res)=>{
res.render('home')
})
Then refresh your browser to see if your form loads
Now in our form we used the name attribute used to specify the name of a form Element lets use our body parser that we installed to the the form elements in our server.js add the following line of code
app.use(express.urlencoded({ extended: false }))
Form Logic
Then we will use a post method to submit our data To post our data we will use the new and save methods
new is used to create a new instance of the data to be posted while the save methods is used to save our data in the database
Add the codes below
app.post("/", async function (req, res) {
const context = new Student({
name: req.body.name,
email: req.body.email,
contact: req.body.contact
})
try{
await context.save()
res.redirect('/success')
}catch(err){
console.log(err)
}
});
Our Success.ejs has the following codes
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>NODEJS FORMS</title>
</head>
<body>
<div class="alert alert-primary" role="alert">
Succesfully submitted
</div>
<a href="/" type="button" class="btn btn-danger">home</a>
</body>
</html>
To render our success page add the following codes to your server.js file
app.get('/success', (req,res)=>{
res.render('success')
})
Test your app by refreshing the localhost://3000 in the browser and the enter some data the see if it will be saved in the database by refreshing your database page
Great job done
Final Code
Our final server.js file looks like
const express = require('express')
require('./db.js')
const Student = require('./Student')
const app = express()
app.set("view engine" , "ejs")
app.use(express.urlencoded({ extended: false }))
app.get('/', (req,res)=>{
res.render('home')
})
app.get('/success', (req,res)=>{
res.render('success')
})
app.post("/", async function (req, res) {
const context = new Student({
name: req.body.name,
email: req.body.email,
contact: req.body.contact
})
try{
await context.save()
res.redirect('/success')
}catch(err){
console.log(err)
}
});
const port = 3000;
app.listen(port, ()=> console.log(`listening on ${port}`))
Find the whole nodeJS forms project using this link