Skip to content
Related Articles

Related Articles

Working with forms using Express.js in Node.js
  • Difficulty Level : Medium
  • Last Updated : 01 Apr, 2021

In this article, we will be working with forms using ExpressJS in NodeJS.

Using server side programming in Node.js, we can create forms where we can put certain parameters which upon filling gets stored in the database.

Setting up environment:

You can refer to this website for downloading Node.js. Along with that, we also have to keep in mind that we are working with something that involves storing of data. For that we need something that can store the information that is submitted from the user end.

We will be using MongoDB for storing up of our data submitted from the form. We should have MongoDB preinstalled in our device before proceeding further. 



You can refer to this website for downloading MongoDB.

After downloading MongoDB, we have to follow some steps before going to the above implementation :

Run "mongod" command at first.
Press 'ctrl+c' and write 'echo "mongod --nojournal" > mongod'
Write 'chmod a+x mongod'

Now, set up the npm package : 

npm init -y

Installing Dependencies:

Use to the following command in the terminal to install the packages at once:

npm install express body-parser mongoose ejs --save

Folder Structure:

Now let us move to the code section.



App.js




//importing dependencies
const express = require("express")
const app=express();
var mongoose=require("mongoose");
var bodyParser=require("body-parser");
  
// Calling form.js from models
var Form=require("./models/form");
  
// Connecting to database
mongoose.connect("mongodb://localhost/form",{
    useNewUrlParser: true,
    useUnifiedTopology: true
});
  
//middlewares
app.set('view engine','ejs');
app.use(bodyParser.urlencoded({extended:true}));
  
//rendering form.ejs
app.get("/",function(req,res){
    res.render("form");
});
  
// form submission
app.get('/result',(req,res)=>{
    res.render('result');
});
  
//creating form
app.post("/",function(req,res){
    var username=req.body.username;
    var email=req.body.email;
    var f={username: username,email:email};
    Form.create(f,function(err,newlyCreatedForm){
        if(err)
        {
            console.log(err);
        }else{
            res.redirect("/result");
        }
    });
});
  
// Starting the server at port 3000
app.listen(3000, function() { 
    console.log('Server running on port 3000'); 
});

Form.js




//Requiring mongoose package
var mongoose=require("mongoose");
  
// Schema
var formSchema=new mongoose.Schema({
    username : String,
    email    : String
});
  
module.exports=mongoose.model("Form",formSchema);

header.ejs




<!DOCTYPE html>
<!-- Opening HTML Tags-->
<html>
    <!-- Opening head Tags-->
<head>
    <!-- Opening head Tags-->
    <title>Form</title>
</head>
<!-- Opening body Tag -->
<body>

form.ejs




<!--Opening the ejs tags for including header file-->
<%- include("./partials/header") %>
<!-- Creating a form where action will 
    be on "/" and the method will be "POST" -->
<form action="/" method="POST">
    <!-- Creating the parameter Username as type= "text"-->
    <label>Username: </label>
    <input type="text" placeholder="Name" name="username"><br><br>
    <!-- Creating the parameter Email as type= "text"-->
    <label>Email: </label>
    <input type="email" placeholder="Email" name="email"><br><br>
    <!-- Creating the submit button -->
    <button>Submit</button>
</form>
<!--Opening the ejs tags for including footer file-->
<%- include("./partials/footer") %>

Output:

Upon filling the form:

Clicking on the submit button, we get redirected to the /result route.

Mongo Shell:

We can see that the information submitted by the form is stored in the database. This is how forms work in node js.

My Personal Notes arrow_drop_up
Recommended Articles
Page :