ExpressJS - Serving Dynamic Content



In Express JS, we can use templating engines like PUG, EJS, Handlebars, Mustache and many more to render dynamic content in an HTML Page. Template engines make life easier by separating HTML from data and logic. We can reuse template components and layouts. We're using PUG as template engine to render a dynamic content in a page. For details on how to install PUG templating engine, you can refer to ExpressJS - Templating.

Apart from PUG as templating engine, we need other libraries useful in html handling.

To install pug, the body-parser and multer, go to your terminal and use −

E:\Dev\hello-world>npm install --save pug body-parser multer
added 37 packages, and audited 128 packages in 1s

20 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Replace your index.js file contents with the following code −

index.js

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.set('view engine', 'pug');
app.set('views', './views');

// for parsing application/json
app.use(bodyParser.json()); 

// for parsing application/xwww-
app.use(bodyParser.urlencoded({ extended: true })); 

app.use(express.static('public'));

app.get('/', function(req, res){
   res.render('form');
});

// handle form submission
app.post('/', function(req, res){
   // read the number entered by the user
   const number = parseInt(req.body.number);
   
   // compute square of the number
   const square = Math.pow(number, 2);

   // return the result
   res.render('form', { result: square });
});
app.listen(3000);

After importing the body parser and multer, we can use the body-parser for parsing json and x-www-form-urlencoded header requests, while we will use multer for parsing multipart/form-data.

Let us create an html form to test this out. Create a new view called form.pug with the following code −

form.pug

html
   head
      title Dynamic Content
   body
      form(action = "/", method = "POST")
         div
            label(for = "number") Enter Number:
            input(name = "number" value = "10")
         br
         button(type = "submit") Calculate
         if(result)
            h3 Square of Number: #{result}

Run your server using the following.

E:\Dev\hello-world>nodemon index.js
[nodemon] 3.1.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node index.js`

Now go to localhost:3000/ and fill the number in the form as you like, and submit it.

form submission

The following response will be displayed −

Response to form submission

Here we can check the result computed on node server on our page as a dynamic content using PUG template.

Advertisements