Express.js Basics
Express.js Basics
Express.js is a minimal, flexible web application framework for Node.js. While Node.js's built-in http module lets you create servers, Express makes it dramatically easier by providing a clean API for routing, middleware, and request handling.
Express is the most popular Node.js framework in the world. Virtually every production Node.js API uses Express or a framework built on top of it.
Why Express Over Raw Node.js?
Here is the same server built with raw Node.js versus Express:
// Raw Node.js — verbose and manual
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello World' }));
} else if (req.url === '/users' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ users: [] }));
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000);
// Express — clean and expressive
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({ message: 'Hello World' });
});
app.get('/users', (req, res) => {
res.json({ users: [] });
});
app.listen(3000, () => console.log('Server running on port 3000'));
Express handles status codes, content types, and routing automatically.
Setting Up Your First Express Server
mkdir express-app
cd express-app
npm init -y
npm install express
// index.js
const express = require('express');
const app = express();
// Parse incoming JSON request bodies
app.use(express.json());
// Parse URL-encoded form data
app.use(express.urlencoded({ extended: true }));
// A simple GET route
app.get('/', (req, res) => {
res.json({
status: 'success',
message: 'Welcome to my API',
version: '1.0.0'
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
The Request and Response Objects
Every route handler receives two objects: req (request) and res (response).
app.get('/demo', (req, res) => {
// Request information
console.log(req.method); // GET
console.log(req.url); // /demo
console.log(req.headers); // { 'content-type': 'application/json', ... }
console.log(req.query); // { page: '1', limit: '10' } from ?page=1&limit=10
console.log(req.params); // Route parameters like :id
console.log(req.body); // JSON body (requires express.json() middleware)
// Response methods
res.status(200).json({ data: 'hello' }); // Send JSON
// res.send('plain text'); // Send text
// res.sendFile('/path/to/file.html'); // Send a file
// res.redirect('/other-route'); // Redirect
});
Route Parameters and Query Strings
// Route parameter — part of the URL path
// URL: GET /users/42
app.get('/users/:id', (req, res) => {
const userId = req.params.id; // '42'
res.json({ userId, message: `Fetching user ${userId}` });
});
// Query string — appended after ?
// URL: GET /products?category=electronics&price=max
app.get('/products', (req, res) => {
const { category, price } = req.query;
res.json({ category, price });
});
// Multiple route parameters
// URL: GET /users/42/posts/7
app.get('/users/:userId/posts/:postId', (req, res) => {
const { userId, postId } = req.params;
res.json({ userId, postId });
});
Sending Different Response Types
// JSON response (most common for APIs)
app.get('/api/data', (req, res) => {
res.status(200).json({ success: true, data: { name: 'Amara' } });
});
// 404 Not Found
app.get('/missing', (req, res) => {
res.status(404).json({ error: 'Resource not found' });
});
// 201 Created (for POST endpoints)
app.post('/users', (req, res) => {
const newUser = { id: 1, ...req.body };
res.status(201).json({ success: true, user: newUser });
});
// 500 Internal Server Error
app.get('/broken', (req, res) => {
res.status(500).json({ error: 'Something went wrong on our end' });
});
Key Takeaways
- Express.js is a minimal Node.js framework that simplifies routing, middleware, and response handling.
- Use
app.get(),app.post(),app.put(), andapp.delete()to define HTTP routes. req.paramsholds route parameters (e.g.,:id), whilereq.queryholds query string values.- Always add
express.json()middleware to parse JSON request bodies. - Use
res.status().json()to send structured JSON responses with appropriate HTTP status codes.
Practice Exercise
- Create an Express server with routes for a simple "users" API:
GET /users— return an array of 3 hardcoded user objectsGET /users/:id— return a single user by IDPOST /users— accept a JSON body and return the new user with a 201 status
- Add a
GET /healthroute that returns{ status: "ok", uptime: process.uptime() }. - Test your routes using a tool like Postman or by visiting them in your browser.
Try it yourself
Key Takeaways
- Express.js eliminates the boilerplate of raw Node.js HTTP servers, providing clean APIs for routing and middleware.
- Every route handler receives req (request) and res (response) objects with helpful properties and methods.
- req.params holds path parameters, req.query holds query string values, and req.body holds the parsed request body.
- Always add express.json() middleware to parse JSON bodies sent by clients.
- Use res.status().json() to send well-formed JSON responses with the correct HTTP status code.
Quick Quiz
1.What is Express.js?
2.Which middleware do you need to add so Express can parse JSON request bodies?
3.How do you access a URL route parameter in Express? For example, the ':id' in '/users/:id'.
4.What HTTP status code should you return when a new resource is successfully created?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx