Welcome to our comprehensive guide on Routing in Raw HTTP with Node.js! This tutorial is designed to help both beginners and intermediate learners understand the concept from scratch. Let's dive in!
Routing is a crucial part of web development that helps in handling different URLs and their corresponding actions. In this tutorial, we'll learn how to implement routing in Node.js using the raw HTTP module.
Before we dive into routing, let's understand what the HTTP module is. The HTTP (HyperText Transfer Protocol) module in Node.js allows you to create an HTTP server, handle requests, and send responses.
Let's start by setting up a basic server using the HTTP module.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});In this example, we're creating a server, listening on port 3000, and responding with 'Hello, World!' for any request.
Now, let's implement basic routing. We'll create different handlers for different URLs.
const http = require('http');
const server = http.createServer((req, res) => {
// Check the URL and send the appropriate response
if (req.url === '/') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Welcome to our homepage!');
} else if (req.url === '/about') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('About us page.');
}
// Default response for any other URL
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404: Page not found.');
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});In this example, we're checking the URL of the request and sending the appropriate response. If the URL is '/', we send 'Welcome to our homepage!', and if the URL is '/about', we send 'About us page.'. For any other URL, we send a 404 error.
Let's create a simple blog where we can list articles and display their content.
const http = require('http');
const url = require('url');
const articles = [
{ title: 'Article 1', content: 'This is the content of Article 1.' },
{ title: 'Article 2', content: 'This is the content of Article 2.' },
];
const server = http.createServer((req, res) => {
const pathName = url.parse(req.url).pathname;
// List articles
if (pathName === '/') {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Articles</h1><ul><li><a href="/article1">Article 1</a></li><li><a href="/article2">Article 2</a></li></ul>');
}
// Display article content
if (pathName.includes('/article')) {
const articleIndex = pathName.split('/')[2];
if (articleIndex >= '1' && articleIndex <= articles.length) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`<h1>${articles[articleIndex - 1].title}</h1><p>${articles[articleIndex - 1].content}</p>`);
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404: Article not found.');
}
}
// Default response for any other URL
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404: Page not found.');
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});In this example, we're listing articles on the homepage and displaying their content when clicking on them.
In the practical example, how do we display the content of an article when clicking on it?
That's it for this tutorial! We've learned how to implement basic routing in Node.js using the raw HTTP module. Happy coding! 🎉