0% found this document useful (0 votes)
11 views7 pages

Routing in Express and Template

The document explains routing in Express, detailing how to handle client requests using various HTTP methods and providing example code for basic routing. It also introduces EJS as a templating engine for rendering dynamic content in Node.js applications, outlining its syntax and usage. Finally, it provides a step-by-step guide on setting up an Express application with EJS for rendering templates.

Uploaded by

tvganesann
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views7 pages

Routing in Express and Template

The document explains routing in Express, detailing how to handle client requests using various HTTP methods and providing example code for basic routing. It also introduces EJS as a templating engine for rendering dynamic content in Node.js applications, outlining its syntax and usage. Finally, it provides a step-by-step guide on setting up an Express application with EJS for rendering templates.

Uploaded by

tvganesann
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Routing in Express

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.).

Express provides methods like:

 app.get() – for GET requests

 app.post() – for POST requests

 app.put() – for PUT requests

 app.delete() – for DELETE requests

Syntax:

app.METHOD(PATH, HANDLER)

 app – the instance of Express

 METHOD – HTTP method (like get, post)

 PATH – route path (like '/', '/about')

 HANDLER – function to handle the request

Example Program: Basic Routing

Create a file called app.js:

const express = require('express');

const app = express();

// Route for Home Page

app.get('/', (req, res) => {

res.send('Welcome to Home Page');

});

// Route for About Page

app.get('/about', (req, res) => {

res.send('This is the About Page');


});

// Route to handle form submission (POST)

app.post('/submit', (req, res) => {

res.send('Form Submitted Successfully!');

});

// Start the server

const PORT = 3000;

app.listen(PORT, () => {

console.log(`Server is running on http://localhost:${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.

1. Create folder in any place


2. Goto cmd
3. Check the following
Node -v
Npm -v
4. Npm install express
5. Open the folder in vscode
6. Add json file
Npm init -y
7.Create app.js file

const express = require("Express") ;

const app = express() ;

const routing = require('./routing');

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.youtube.com/">youtube</a>

<a href="https://www.tutorialpoint.com">TutorialPoint</a>

</body>

</html>

9.Create rouring.js

const express = require("express") ;

const router= express.Router() ;

router.get('/', function(req, res)

res.sendFile(__dirname +"/"+"index.html");

);

module.exports = router;

9.save and rin the program

>node app.js

Output
A template engine lets you embed JavaScript code into HTML. You can use it to:

 Dynamically insert values (like a username)

 Loop through arrays (like a product list)

 Include conditions (like if-else)

Popular template engines are EJS, Pug, Handlebars, etc.

EJS (Embedded JavaScript Templates) – it's simple and widely used.

EJS stands for Embedded JavaScript. It’s a simple templating language that lets you generate HTML
markup using plain JavaScript.

What is it used for?

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.

How does EJS work?

You write regular HTML but can insert JavaScript logic like:

 Variables

 Loops

 Conditionals

Example:

<h1>Hello <%= name %>!</h1>

<% if (userLoggedIn) { %>

<p>Welcome back!</p>

<% } else { %>

<p>Please log in.</p>

EJS Tag

<% } %>
 <%= %> outputs escaped content (for HTML safety)

 <%- %> outputs raw, unescaped content

 <% %> runs logic without outputting anything

Example

<%=%>

<% let name = "Alice"; %>

<% let bio = "<strong>I love coding!</strong>"; %>

<h1>Welcome, <%= name %>!</h1> <!-- Escaped output -->

<%-%>

<p>About me (escaped): <%= bio %></p> <!-- Will display HTML as text -->

<p>About me (raw): <%- bio %></p> <!-- Will render bold HTML -->

<%{%>

<% if (name === "Alice") { %>

<p>Hello, Alice! Nice to see you again.</p>

<% } else { %>

<p>Hello, guest!</p>

<% } %>

Why use EJS?

 Easy to learn (especially if you know HTML and JavaScript)

 Integrates well with Express.js

 Lets you build dynamic web pages quickly

Common Usage in Express:

const express = require('express');

const app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {

res.render('index', { name: 'Alice', userLoggedIn: true });

});

Then your views/index.ejs could use that data to render HTML.

Example
Steps to Use a Template in Express (with EJS)

1. Install EJS

npm install express ejs

2. Project Structure

EJS/

├── app.js

└── views/

└── index.ejs

3. Sample Code: app.js

const express = require('express');

const app = express();

// Set EJS as the template engine

app.set('view engine', 'ejs');

// Route that renders a template

app.get('/', (req, res) => {

const userName = "Alice";

res.render('index', { name: userName });

});

const PORT = 3000;

app.listen(PORT, () => {

console.log(`Server running at http://localhost:${PORT}`);

});

4. Template File: views/index.ejs

<!DOCTYPE html>

<html>

<head>
<title>Home Page</title>

</head>

<body>

<h1>Hello, <%= name %>!</h1>

<p>Welcome to the Express Template Example.</p>

</body>

</html>

You might also like