Nodejs

Node JS Routing And Render Html File

Node JS Routing And Render Html File - The Rich Post

node_routing
178Views

Hello to all, welcome to therichpost.com. In this post, I will tell, Node JS Routing And Render Html File.

Routing is very important part of every website or application. 

With time, everything changes, like today is world of single page application, which makes Javascript on the top.

Today I will discuss, Node Js Routing and Render Html File and I think this is very interesting.

Here is my test file structure:

 

Node JS Routing And Render Html File

 

Here are the working steps need to follow:

 

1. First, you need to install below npm packages into your nodejs application:
So you need to run below commands into your terminal:
npm install express

npm install ejs
2. Second, you need to add below code into testcode.js file

This is main file of my nodejs example:

var express = require('Express');
var app = express();
var things = require('./things.js');
app.use('/things', things);
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.listen(3000);
3. Now, you need to add below code, into your things.js file:

In this file,  we creates router(file path) and also I define the title(title: ‘Express Index File’):

var express = require('express');
var router = express.Router();

router.get('/test', function(req, res){
    res.render('index.html', {
            title: 'Express Index File'
        });
});
//export this router to use in our testcode.js
module.exports = router;
4. Create index.html file, into view folder in node js application:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Index Page</h1>
</body>
</html>
 
5. After this, you need to run below command into your terminal:
node testcode.js

This is it, if you have any query related to  this post then please do comment below or ask question.

Thank you,

Gabru Nu Kehnde AA trend Baliye

TheRichPost

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

Positive SSL