How to Handle Routing in Node.js: Simple Guide with Express
Express framework, which lets you define URL paths and their handlers easily with methods like app.get() and app.post(). Without Express, you must manually parse the request URL and method, which is complex and error-prone. Using Express simplifies routing and improves code clarity.Why This Happens
When you try to handle routing in Node.js without a framework like Express, you must manually check the request URL and HTTP method. This often leads to complicated and hard-to-maintain code. Developers new to Node.js sometimes write code that does not correctly route requests, causing errors or unexpected behavior.
import http from 'http'; const server = http.createServer((req, res) => { if (req.url === '/home' && req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Welcome to Home Page'); } else if (req.url === '/about' && req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('About Us'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Page Not Found'); } }); server.listen(3000);
The Fix
Use the Express framework to handle routing cleanly. Express provides simple methods like app.get() and app.post() to define routes and their handlers. This makes your code easier to read, maintain, and extend.
import express from 'express'; const app = express(); app.get('/home', (req, res) => { res.send('Welcome to Home Page'); }); app.get('/about', (req, res) => { res.send('About Us'); }); app.use((req, res) => { res.status(404).send('Page Not Found'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Prevention
Always use a routing framework like Express for Node.js projects to avoid complex manual routing. Keep routes organized by grouping related routes in separate files or using express.Router(). Use linting tools like ESLint to catch common mistakes early. Write clear route handlers and test routes regularly to ensure they work as expected.
Related Errors
Common routing errors include missing route handlers causing 404 errors, incorrect HTTP method checks leading to unexpected responses, and forgetting to call res.end() or res.send() causing requests to hang. Using Express helps prevent these by providing clear routing methods and automatic response handling.