← Back to Examples

Express.js Basics

Follow along! Create these files on your computer and run with node index.js.

Step 1: Project Setup

1 Create project and install Express
$ mkdir express-demo $ cd express-demo $ npm init -y $ npm install express

Step 2: Hello World Server

2 Create index.js
// index.js const express = require('express'); const app = express(); const PORT = 3000; // Home route app.get('/', (req, res) => { res.send('<h1>Hello World!</h1><p>Welcome to Express.js</p>'); }); // About route app.get('/about', (req, res) => { res.send('<h1>About Page</h1><p>This is a simple Express app.</p>'); }); // JSON response app.get('/api/status', (req, res) => { res.json({ status: 'running', timestamp: new Date().toISOString(), uptime: process.uptime() }); }); // Start server app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`); console.log('Press Ctrl+C to stop'); });
$ node index.js Server running at http://localhost:3000 # Open http://localhost:3000 in your browser

Step 3: Route Parameters

// routes-demo.js const express = require('express'); const app = express(); // Static route app.get('/products', (req, res) => { res.json([ { id: 1, name: 'Laptop', price: 999 }, { id: 2, name: 'Phone', price: 699 } ]); }); // Dynamic route with URL parameter app.get('/products/:id', (req, res) => { const { id } = req.params; res.json({ message: `Fetching product ${id}` }); }); // Multiple parameters app.get('/users/:userId/posts/:postId', (req, res) => { const { userId, postId } = req.params; res.json({ message: `User ${userId}, Post ${postId}` }); }); // Query parameters // GET /search?q=laptop&sort=price&order=asc app.get('/search', (req, res) => { const { q, sort, order } = req.query; res.json({ query: q, sort: sort || 'relevance', order: order || 'desc', results: [] }); }); app.listen(3000, () => console.log('Server on :3000'));

Step 4: Serving Static Files

// static-server.js const express = require('express'); const path = require('path'); const app = express(); // Serve files from 'public' directory // Files accessible at: http://localhost:3000/filename app.use(express.static('public')); // Serve files from 'uploads' with prefix // Files accessible at: http://localhost:3000/files/filename app.use('/files', express.static('uploads')); // Serve index.html for root app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); app.listen(3000, () => console.log('Static server on :3000')); // Project structure: // express-demo/ // public/ // index.html // style.css // script.js // images/ // logo.png // uploads/ // static-server.js

Step 5: Middleware

// middleware-demo.js const express = require('express'); const app = express(); // Built-in middleware app.use(express.json()); // Parse JSON bodies app.use(express.urlencoded({ // Parse form data extended: true })); app.use(express.static('public')); // Serve static files // Custom middleware - Request Logger app.use((req, res, next) => { const timestamp = new Date().toISOString(); console.log(`[${timestamp}] ${req.method} ${req.url}`); next(); // MUST call next() to continue }); // Custom middleware - Add request time app.use((req, res, next) => { req.requestTime = Date.now(); next(); }); // Route-specific middleware function requireAuth(req, res, next) { const token = req.headers['authorization']; if (!token) { return res.status(401).json({ error: 'Not authorized' }); } // In real app: verify token next(); } // Public route - no auth needed app.get('/api/public', (req, res) => { res.json({ message: 'Public data' }); }); // Protected route - auth middleware applied app.get('/api/private', requireAuth, (req, res) => { res.json({ message: 'Secret data!' }); }); // Error handling middleware (4 parameters!) app.use((err, req, res, next) => { console.error('Error:', err.message); res.status(500).json({ error: 'Something went wrong!' }); }); app.listen(3000);

Step 6: Handling POST Data

// post-demo.js const express = require('express'); const app = express(); // IMPORTANT: Parse JSON request bodies app.use(express.json()); // In-memory storage const messages = []; // Serve a simple form app.get('/', (req, res) => { res.send(` <h1>Message Board</h1> <form action="/messages" method="POST"> <input name="author" placeholder="Your name" required> <input name="text" placeholder="Your message" required> <button type="submit">Send</button> </form> <h2>Messages:</h2> <ul> ${messages.map(m => `<li><strong>${m.author}:</strong> ${m.text}</li>` ).join('')} </ul> `); }); // Handle form submission app.use(express.urlencoded({ extended: true })); app.post('/messages', (req, res) => { const { author, text } = req.body; messages.push({ id: messages.length + 1, author, text, createdAt: new Date().toISOString() }); res.redirect('/'); }); // JSON API endpoint app.post('/api/messages', (req, res) => { const { author, text } = req.body; if (!author || !text) { return res.status(400).json({ error: 'Author and text are required' }); } const message = { id: messages.length + 1, author, text, createdAt: new Date().toISOString() }; messages.push(message); res.status(201).json(message); }); app.listen(3000, () => { console.log('Message board on http://localhost:3000'); });
Testing POST requests: Use the browser form, or test with curl:
$ curl -X POST http://localhost:3000/api/messages \ -H "Content-Type: application/json" \ -d '{"author":"Alice","text":"Hello!"}'

← Back to Examples