a blog for those who code

Thursday, 23 March 2017

How to Render Static HTML file in ExpressJS 4

In this post we will be discussing about rendering static HTML files in Express.js. There are number of options to render static HTML files in Express.js. Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications.

Render Static HTML file using res.sendFile()

res.sendFile() transfers the file at the given path and also invokes a callback function when the transfer is either failed or it succeeded.

Simple Example :

// Static HTML File which is to be rendered
<html>
 <body>
  <form action="" method="post" enctype="multipart/form-data">
   <fieldset>
    <label for="loginname">Login Name : </label>
    <input type="text" id="loginname" name="loginname" placeholder="Enter Login Name" />
    <br/><br/>
    <label for="email">Email : </label>
    <input type="email" id="email" name="email" placeholder="Enter Email" />
<br/><br/>
    <input type="submit" value="Submit Record" />
   </fieldset>
</form>
</body>
</html>

// Rendering the HTML file through Express

var express = require('express');
var app = express();
app.get('/', function(req,res) {
 res.sendFile(__dirname + '/index.html');
})
app.listen(8010);
console.log('Express App is running on port 8010...');

Output :

Render Static HTML file using using res.render()

res.render() renders a view and sends the rendered HTML string to the client.

Simple Example :

// HTML File will be same as above
var express = require('express');
var app = express();
app.get('/', function(req,res) {
  res.render(__dirname + '/index.html');
})
app.listen(8010);
console.log('Express App is running on port 8010...');

How to solve Cannot find module 'html'

If you are getting the error "Cannot find module 'html'" which means that your express is not able to render the HTML file. For that you need to set the engine as html. To do that at first we need to install ejs module by the command npm install ejs --save and then use the following code.

var express = require('express');
var app = express();

// Mapping the EJS template engine to ".html" files
app.engine('html', require('ejs').renderFile);

app.get('/', function(req,res) {
 res.render(__dirname + '/index.html');
})
app.listen(8010);
console.log('Express App is running on port 8010...');

How to solve "TypeError: path must be absolute or specify root to res.sendFile"

If you are getting this error means that the file path you have assigned is not correct.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment