Implementing Dynamic Routing
To create a more dynamic routing system, we need to differentiate responses based on the URL entered by the user. Here’s how we can achieve this:
Extracting the URL: We can access the requested URL through the
request
parameter in our callback function. Therequest.url
property contains the value entered after the root URL.Creating a Path Variable: We will create a variable called
path
and assign it the value ofrequest.url
. This allows us to determine which page the user is trying to access.Sending Different Responses: Based on the value of the
path
variable, we can send different responses. For example:If the path is
/
, we will return a response indicating that the user is on the home page.If the path is
/home
, we will also return a response for the home page.If the path is
/about
, we will return a response for the about page.If the path is
/contact
, we will return a response for the contact page.
Example Code Implementation
Here’s a simplified version of how the code would look:
const http = require('http');
const server = http.createServer((request, response) => {
const path = request.url.toLowerCase();
if (path === '/') {
response.end('You are in home page');
} else if (path === '/home') {
response.end('You are in home page');
} else if (path === '/about') {
response.end('You are in about page');
} else if (path === '/contact') {
response.end('You are in contact page');
} else {
response.end('Error 404: Page not found');
}
});
server.listen(8000);
Handling Unhandled Routes
One important aspect of routing is handling URLs that do not match any defined routes. For instance, if a user types /products
, our server should not hang indefinitely. To prevent this, we implement a fallback route that returns a 404 error message when the requested URL does not match any of our defined routes.
Adding a Fallback Route
In our code, we added an else
statement at the end of our routing logic to handle unrecognized paths. This ensures that if a user enters a URL that we are not handling, they receive a clear message indicating that the page was not found.