Node.js — Express
Installation
npm install express
Basic Express App
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Routing
// GET
app.get('/users', (req, res) => {
res.json(users);
});
// POST
app.post('/users', (req, res) => {
const user = req.body;
users.push(user);
res.status(201).json(user);
});
// PUT
app.put('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);
Object.assign(user, req.body);
res.json(user);
});
// DELETE
app.delete('/users/:id', (req, res) => {
users = users.filter(u => u.id !== parseInt(req.params.id));
res.sendStatus(204);
});
Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Custom middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
Mini Practice
- Create an Express app
- Set up routes
- Add middleware
- Handle different HTTP methods
Up Next
Continue with Middleware — Express middleware patterns.
Related Topics
Frequently Asked Questions about Express
What is Express in Node.js?
Express is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Express?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Express.
Why is Express important in Node.js?
Express is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.