Routing with Node’s http Module
Introduction
In this lesson, we will explore routing using Node's built-in http
module.
Routing is a key part of web applications, allowing you to define how your application
responds to client requests at various endpoints.
Node's http Module
The http
module in Node.js allows you to create HTTP servers and make HTTP requests.
It provides an interface for sending and receiving data over HTTP. Here's a brief overview of its
key features:
- Creating a server using
http.createServer()
- Handling requests and responses
- Defining routes based on request URLs
Routing Basics
Routing involves mapping a request URL to a specific function that will handle the request.
This allows different responses for different endpoints. The basic structure for routing with
the http
module involves checking the request.url
property.
Creating a Simple Server
Below is a simple example to demonstrate how to create a server and implement routing using Node’s
http
module.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the Home Page!');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('This is the About Page!');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
In this example, we are checking the req.url
property to determine which response
to send back based on the requested URL.
Best Practices
When working with Node's http module and routing, consider the following best practices:
- Keep your route handlers modular and organized.
- Use middleware for common tasks like logging and authentication.
- Always send a response to avoid hanging requests.
FAQ
What is the difference between Node's http module and Express?
Node's http module is a low-level API for creating HTTP servers. Express is a higher-level framework that adds additional features and simplifies routing.
Can I use other HTTP methods like POST and PUT?
Yes! You can handle other HTTP methods by checking the req.method
property
in your request handler.