Creating Routes and Handling Requests with Express
Also onpreet-jain.hashnode.dev/creating-routes-and-handling-requests-with-expressIf you've built a server with raw Node's http module, you know the drill—parsing URLs, checking methods, writing response headers, handling the whole thing in a giant if-else chain. It's not impossible, but it's verbose. Express.js abstracts all that boilerplate away so you can focus on what actually matters: your routes and logic.
What Express Actually Is
Express is a minimal web framework for Node.js. It sits on top of Node's HTTP module and gives you a clean API for building web servers. Think of it as a thin layer that handles the boring stuff—routing, request parsing, middleware—so you don't have to.
Raw Node vs Express
Here's what a simple "hello world" looks like with raw Node:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World');
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000);Now here's the same thing in Express:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000);Notice the difference. No manual URL parsing, no method checking, no writing headers. Express handles the request-response cycle, and you just define what happens for each route.
Your First Express Server
Install it first:
npm install expressThen set up the basics:
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('Server running on port 3000');
});That's it. You have a running server. Now add some routes.
Handling GET Requests
GET requests are the simplest. Use app.get():
app.get('/users', (req, res) => {
res.json([
{ id: 1, name: 'Alex' },
{ id: 2, name: 'Sam' }
]);
});
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`Fetching user ${userId}`);
});The :id part is a route parameter. Access it via req.params.id.
Handling POST Requests
For POST, PUT, DELETE—use the matching method:
app.post('/users', (req, res) => {
console.log('Received:', req.body);
res.status(201).json({ message: 'User created' });
});Here's the thing: Express doesn't parse the request body by default. You need a middleware. The built-in express.json() handles JSON payloads:
app.use(express.json());
app.post('/users', (req, res) => {
const newUser = req.body;
console.log('Received:', newUser);
res.status(201).json({ message: 'User created' });
});Sending Responses
Express gives you convenient methods:
res.send() // Sends anything (string, object, array)
res.json() // Sends JSON with proper headers
res.status() // Set HTTP status code (chainable)
res.sendFile() // Send a file
res.redirect() // Redirect to another URLChaining is clean:
res.status(404).json({ error: 'Not found' });Express makes Node.js server development feel straightforward. You define routes, handle requests, send responses. The framework handles the glue code. Once you see how much boilerplate it removes compared to raw Node, you'll understand why it's the go-to choice for building APIs and web servers in Node.