Express.js is the most popular web framework for Node.js, simplifying server creation with powerful features for web and mobile applications. Let’s explore its core concepts.
1. Why Use Express.js?
Key Benefits
- Minimal and flexible
- Robust routing
- Middleware support
- Great for APIs and web apps
- Huge ecosystem
Comparison
// Native Node.js
http.createServer((req, res) => {
if (req.url === '/') {
res.end('Home');
}
// More manual routing...
});
// Express.js
app.get('/', (req, res) => {
res.send('Home');
});
2. Basic Express Application
const express = require('express');
const app = express();
const PORT = 3000;
// Basic route
app.get('/', (req, res) => {
res.send('Hello Express!');
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
3. Core Express Concepts
Routing
// Basic routes
app.get('/products', (req, res) => { /* ... */ });
app.post('/products', (req, res) => { /* ... */ });
// Route parameters
app.get('/products/:id', (req, res) => {
res.send(`Product ID: ${req.params.id}`);
});
// Route chaining
app.route('/users')
.get((req, res) => { /* GET handler */ })
.post((req, res) => { /* POST handler */ });
Middleware
// Application-level middleware
app.use((req, res, next) => {
console.log('Request received at', new Date());
next(); // Pass control to next middleware
});
// Built-in middleware
app.use(express.json()); // Parse JSON bodies
app.use(express.urlencoded({ extended: true })); // Parse form data
4. Serving Static Files
// Serve files from 'public' directory
app.use(express.static('public'));
// Example structure:
// public/
// css/style.css
// js/app.js
// images/logo.png
// Now accessible at:
// /css/style.css
// /js/app.js
// /images/logo.png
5. Handling Different Response Types
Response Type | Method | Example |
---|---|---|
HTML | res.send() | res.send('<h1>Hello</h1>') |
JSON | res.json() | res.json({ user: 'John' }) |
File | res.sendFile() | res.sendFile('/file.pdf') |
Status Code | res.status() | res.status(404).send('Not found') |
6. Error Handling
// Basic error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// Async error handling
app.get('/async-route', async (req, res, next) => {
try {
const data = await fetchData();
res.json(data);
} catch (err) {
next(err); // Pass to error handler
}
});
7. Project Structure Best Practices
my-express-app/
├── node_modules/
├── public/
│ ├── images/
│ ├── css/
│ └── js/
├── routes/
│ ├── index.js
│ ├── users.js
│ └── products.js
├── views/
│ └── index.ejs
├── app.js
├── package.json
└── .env
8. Complete Express Example
const express = require('express');
const path = require('path');
const app = express();
// Middleware
app.use(express.json());
app.use(express.static('public'));
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'index.html'));
});
app.get('/api/users', async (req, res, next) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
next(err);
}
});
// Error handler
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});
// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
Next: Building RESTful APIs with Express →
Express.js Cheat Sheet
app.get/post/put/delete()
– Route handlersapp.use()
– Middleware registrationreq.params
– Route parametersreq.query
– URL query parametersreq.body
– Request body data