Routing in Node.
js
Routing in [Link]
• Routing in [Link] refers to the process of determining how an incoming HTTP
request should be handled and which code or function should be executed to
generate the appropriate response.
• Routing is a fundamental part of building web applications and APIs.
• Routing can be implemented using a web framework or without any framework.
Routing without framework
• Routing without a framework involves manually handling HTTP requests and writing
custom code to determine how each request should be handled.
Routing without framework
const http = require('http');
const server = [Link]((req, res) => {
if ([Link] === '/') {
[Link](200, { 'Content-Type': 'text/plain' });
[Link]('Welcome to the homepage!');
} else if ([Link] === '/about') {
[Link](200, { 'Content-Type': 'text/plain' });
[Link]('About Us Page');
} else {
[Link](404, { 'Content-Type': 'text/plain' });
[Link]('Page Not Found');
}
});
const PORT = 3000;
[Link](PORT, () => {
[Link](`Server is listening on port ${PORT}`);
});
Routing with framework - [Link]
• Using a web framework like [Link] makes routing much more organized and
efficient. Express simplifies the process of defining routes and handling HTTP
requests.
Routing with framework - [Link]
const express = require('express');
const app = express();
// Define routes
[Link]('/', (req, res) => {
[Link]('Welcome to the homepage!');
});
[Link]('/about', (req, res) => {
[Link]('About Us Page');
});
// Handle 404 errors
[Link]((req, res) => {
[Link](404).send('Page Not Found');
});
const PORT = 3000;
[Link](PORT, () => {
[Link](`Server is listening on port ${PORT}`);
});
Routing with & without framework - Key Difference
• Ease of Use: Using a framework like Express simplifies routing and makes it more
intuitive.
• Organized Code: Frameworks encourage a more organized and modular code
structure, making it easier to manage routes as your application grows.
• Middleware: Express allows you to use middleware functions for tasks like
authentication, logging, and error handling, which can be easily integrated into your
routing.
• Community Support: Frameworks have large communities with extensive
documentation and plugins, making it easier to find solutions to common problems.
?