Handling Routes
In the previous chapter, we created a simple server that responded the same way to every request. But real websites have many pages – home, about, contact, etc. To handle different pages, we need **routing**. Routing means directing requests to different handlers based on the URL.
What is Routing?
Routing is the mechanism that maps URLs to specific pieces of code. When a user visits `/about`, the server knows to send the about page. When they visit `/contact`, it sends the contact page.
Think of routing as a receptionist in an office. When someone comes in, the receptionist asks where they want to go and directs them to the right room. Your server does the same with URLs.
The Request URL
Every request has a `url` property that tells you what path the user requested. For example, if someone visits `http://localhost:3000/about`, `req.url` will be `'/about'`.
const http = require('http');
const server = http.createServer((req, res) => { console.log(req.url); <!-- Logs the requested URL --> res.end('Check your console');});Basic Routing with if/else
The simplest way to handle routes is with `if`/`else` statements checking `req.url`.
const http = require('http');
const server = http.createServer((req, res) => { <!-- Set default content type --> res.writeHead(200, { 'Content-Type': 'text/html' }); if (req.url === '/') { res.end('Welcome to the Home Page
'); } else if (req.url === '/about') { res.end('About Us
We are learning Node.js!
'); } else if (req.url === '/contact') { res.end('Contact Us
Email: info@example.com
'); } else { <!-- 404 page --> res.writeHead(404); res.end('404 - Page Not Found
'); }});
server.listen(3000, () => { console.log('Server running on port 3000');});Handling Different HTTP Methods
You might also want to handle different HTTP methods (GET, POST, PUT, DELETE) for the same URL. The `req.method` property tells you which method was used.
const server = http.createServer((req, res) => { if (req.url === '/users') { if (req.method === 'GET') { res.end('List of users'); } else if (req.method === 'POST') { res.end('Create a new user'); } }});A Better Way: Using an Object for Routes
For larger applications, if/else chains become messy. You can use an object to map routes to handler functions.
const http = require('http');
const routes = { '/': (req, res) => { res.end('Home Page'); }, '/about': (req, res) => { res.end('About Page'); }, '/contact': (req, res) => { res.end('Contact Page'); }};
const server = http.createServer((req, res) => { const handler = routes[req.url]; if (handler) { handler(req, res); } else { res.writeHead(404); res.end('404 Not Found'); }});
server.listen(3000);Two Minute Drill
- Routing directs requests to different handlers based on URL.
- Access the requested path with `req.url`.
- Use `if/else` or a routes object to handle different URLs.
- Check `req.method` to handle different HTTP methods.
- Always include a 404 handler for unmatched routes.
- Organizing routes in an object makes code cleaner for many routes.
Need more clarification?
Drop us an email at career@quipoinfotech.com
