Express.js Getting Started
Master Express.js web framework. Understand what Express is, why use it, architecture, routing, and middleware concepts.
Express.js Getting Started
What is Express?
Express is a **minimal and flexible** web framework for Node.js. It makes building web servers much easier.
The Problem: Building Servers with Node.js
Without Express, you need to handle everything manually:
```javascript const http = require('http');
const server = http.createServer((req, res) => { if (req.url === '/users' && req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify([{ id: 1, name: 'John' }])); } else if (req.url === '/users' && req.method === 'POST') { let body = ''; req.on('data', chunk => body += chunk); req.on('end', () => { const user = JSON.parse(body); res.writeHead(201); res.end(JSON.stringify(user)); }); } else { res.writeHead(404); res.end('Not Found'); } });
server.listen(3000); ```
**Problems:** - Manual URL parsing - Manual method checking - Manual body parsing - Manual headers - Lots of boilerplate code
The Solution: Express
Express simplifies everything:
```javascript const express = require('express'); const app = express();
app.get('/users', (req, res) => { res.json([{ id: 1, name: 'John' }]); });
app.post('/users', (req, res) => { res.status(201).json(req.body); });
app.listen(3000); ```
**Benefits:** - Automatic routing - Automatic body parsing - Clean syntax - Middleware support - Less code, more features
Express Architecture
``` ┌─────────────────────────────────┐ │ HTTP Request │ └──────────────┬────────────────────┘ │ ┌──────────────▼────────────────────┐ │ Express App │ │ ┌────────────────────────────┐ │ │ │ Middleware Stack │ │ │ │ - Body parser │ │ │ │ - CORS │ │ │ │ - Authentication │ │ │ │ - Logging │ │ │ └────────────────────────────┘ │ │ ┌────────────────────────────┐ │ │ │ Router │ │ │ │ - GET /users │ │ │ │ - POST /users │ │ │ │ - PUT /users/:id │ │ │ └────────────────────────────┘ │ └──────────────┬────────────────────┘ │ ┌──────────────▼────────────────────┐ │ HTTP Response │ └─────────────────────────────────────┘ ```
Why Use Express?
**1. Simplifies Routing** ``` Without Express: Manual URL parsing, if/else chains With Express: Clean route definitions ```
**2. Middleware Support** ``` Request → Middleware 1 → Middleware 2 → Route Handler → Response ```
**3. Large Ecosystem** - Thousands of middleware packages - Well-documented - Community support
**4. Industry Standard** - Used by Netflix, Uber, PayPal - Most Node.js jobs require Express - Best practices established
Installation
```bash npm init -y npm install express ```
Hello World
```javascript const express = require('express'); const app = express();
app.get('/', (req, res) => { res.send('Hello World!'); });
app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); ```
Basic Routing
```javascript // GET request app.get('/users', (req, res) => { res.json([{ id: 1, name: 'Alice' }]); });
// POST request app.post('/users', (req, res) => { res.status(201).json({ message: 'User created' }); });
// PUT request app.put('/users/:id', (req, res) => { res.json({ message: `Updated user ${req.params.id}` }); });
// DELETE request app.delete('/users/:id', (req, res) => { res.json({ message: `Deleted user ${req.params.id}` }); }); ```
Route Parameters
```javascript // /users/123 app.get('/users/:id', (req, res) => { const userId = req.params.id; // '123' res.json({ id: userId }); });
// /posts/2024/01 app.get('/posts/:year/:month', (req, res) => { const { year, month } = req.params; res.json({ year, month }); }); ```
Query Parameters
```javascript // /search?q=nodejs&limit=10 app.get('/search', (req, res) => { const query = req.query.q; // 'nodejs' const limit = req.query.limit; // '10' res.json({ query, limit }); }); ```
Request Body (JSON)
```javascript // Enable JSON parsing app.use(express.json());
app.post('/users', (req, res) => { const { name, email } = req.body; console.log('Received:', name, email); res.status(201).json({ name, email }); }); ```
Response Methods
```javascript app.get('/demo', (req, res) => { // Send text res.send('Hello'); // Send JSON res.json({ message: 'Hello' }); // Set status + send res.status(404).json({ error: 'Not found' }); // Send file res.sendFile('/path/to/file.pdf'); // Redirect res.redirect('/new-url'); }); ```
Basic Error Handling
```javascript app.get('/users/:id', (req, res) => { const user = findUser(req.params.id); if (!user) { return res.status(404).json({ error: 'User not found' }); } res.json(user); }); ```
Complete Example
```javascript const express = require('express'); const app = express();
// Middleware app.use(express.json());
// In-memory "database" let users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ];
// Get all users app.get('/api/users', (req, res) => { res.json(users); });
// Get one user app.get('/api/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) return res.status(404).json({ error: 'Not found' }); res.json(user); });
// Create user app.post('/api/users', (req, res) => { const user = { id: users.length + 1, name: req.body.name }; users.push(user); res.status(201).json(user); });
// Update user app.put('/api/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) return res.status(404).json({ error: 'Not found' }); user.name = req.body.name; res.json(user); });
// Delete user app.delete('/api/users/:id', (req, res) => { users = users.filter(u => u.id !== parseInt(req.params.id)); res.status(204).send(); });
app.listen(3000, () => console.log('Server running on port 3000')); ```
Key Takeaway
Express simplifies Node.js web development. Define routes with `app.get()`, `app.post()`, etc. Access params with `req.params`, query with `req.query`, body with `req.body`. Respond with `res.json()` or `res.send()`. That's the foundation!