Open In App

How to dynamically add HTML content when documents are inserted in collection using Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, you will learn about making your Node application responsive so that it will automatically change HTML content & update it with the new content inserted in the collection. 

We are going to set up a middleware EJS, EJS makes it easy to send data from your server file (app.js or server.js) to a static page (HTML). After that, we are going to use Body Parser by which we can capture user input values from the form & store them in a collection, then we are going to send the data of the collection to the static page. In this way, when any data is inserted into the form then it inserts into the collection & automatically updates the HTML content.  

Install EJS: Locate your root project directory into the terminal and type the command

npm install ejs

Set EJS as view engine:

app.set('view engine', 'ejs');

Rearrange Your Directories: It is required to rename your file from .html to .ejs for using EJS inside it. Then you have to move every single .ejs file in the views directory inside your root directory.

Use EJS variable: Inside your updated .ejs file, you have to use EJS Variables to receive values from your server file.

HTML




<!DOCTYPE html>
<html>
    
<head>
    <title>Page Title</title>
</head>
    
<body>
    <%= variableName %>
</body>
  
</html>


Send data to a variable: Inside your server file ( app.js or index.js ), you can send an EJS file along with some data by using the render method.

Javascript




const express = require('express')
const app = express()
app.set('view engine', 'ejs')
  
app.get("/", (req, res) => {
  res.render("home", { variableName: "Hello World!" })
})
  
app.listen(3000, (req, res) => {
  console.log("App is running on port 3000")
})


Fetching data from form to app.js: To receive input values of a form, we have to use a node package named body-parser.

Install body-parser:

npm install body-parser

Require body-parser module:

var bodyParser = require('body-parser')

And then

app.use( bodyParser.json() );      
    app.use(bodyParser.urlencoded({    
        extended: true
    })
)

Then we can handle form data using the request object.

Example: Suppose there is a collection of name data, inside data, there are elements containing title and content. So we have to send those elements to the Home file so that it displays it. We also concurrently make a post route that handles the post request from the home page, stores the form input, and inserts it into the collection.

App.js file

Javascript




const express = require('express')
const bodyParser = require('body-parser')
const data = [{
    title: "This is first blog",
    content: "This is first blog content."
},
{
    title: "This is second blog",
    content: "This is second blog content."
},
{
    title: "This is third blog",
    content: "This is third blog content."
}
]
  
const app = express()
  
app.set('view engine', 'ejs')
  
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}))
  
app.get("/", (req, res) => {
    res.render("home", {
        data: data
    })
})
  
app.post("/", (req, res) => {
    const inputTitle = req.body.inputTitle
    const inputContent = req.body.inputContent
    data.push({
        title: inputTitle,
        content: inputContent
    })
    res.render("home", {
        data: data
    })
})
  
app.listen(3000, (req, res) => {
    console.log("App is running on port 3000")
})


Home.ejs file: We have to use For Each Loop to loop through every single object inside our collection and display the title and content. We also have to set up a form for submitting new titles and content.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Page Title</title>
</head>
  
<body>
    <% data.forEach(element => { %>
    <h2><%= element.title %></h2>
      
<p><%= element.content %></p>
  
    <% }) %>
  
    <form action="/" method="post">
        <input type="text" placeholder="Title" name="inputTitle">
        <input type="text" placeholder="Content" name="inputContent">
        <button type="submit">Submit</button>
    </form>
</body>
  
</html>


Output:

 



Last Updated : 05 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads