Categories

Saturday, October 12, 2024
#919814419350 therichposts@gmail.com
Nodejs

Node JS Routing And Render Html File

Node JS Routing And Render Html File - The Rich Post

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

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.