Routing in Express and Template
Routing in Express and Template
Routing refers to how an application responds to a client request to a particular endpoint (a URI or
path) and a specific HTTP method (GET, POST, etc.).
Syntax:
app.METHOD(PATH, HANDLER)
});
});
app.listen(PORT, () => {
});
ExpressRouter()
express.Router() is like a mini Express application that can handle its own routes. It helps you
modularize your code by grouping related routes.
app.use('/',routing)
app.listen(3000, () =>
{ console.log("listening on http://localhost:3000"); })
8.Create index.html
Add the following
<html>
<body>
<a href="https://www.tutorialpoint.com">TutorialPoint</a>
</body>
</html>
9.Create rouring.js
res.sendFile(__dirname +"/"+"index.html");
);
module.exports = router;
>node app.js
Output
A template engine lets you embed JavaScript code into HTML. You can use it to:
EJS stands for Embedded JavaScript. It’s a simple templating language that lets you generate HTML
markup using plain JavaScript.
EJS is mostly used in Node.js applications (especially with Express.js) to render dynamic content on
the server side before sending it to the browser.
You write regular HTML but can insert JavaScript logic like:
Variables
Loops
Conditionals
Example:
<p>Welcome back!</p>
EJS Tag
<% } %>
<%= %> outputs escaped content (for HTML safety)
Example
<%=%>
<%-%>
<p>About me (escaped): <%= bio %></p> <!-- Will display HTML as text -->
<p>About me (raw): <%- bio %></p> <!-- Will render bold HTML -->
<%{%>
<p>Hello, guest!</p>
<% } %>
});
Example
Steps to Use a Template in Express (with EJS)
1. Install EJS
2. Project Structure
EJS/
├── app.js
└── views/
└── index.ejs
});
app.listen(PORT, () => {
});
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
</body>
</html>