Built-in middleware and third-party middleware
The middleware mechanism in the Express framework is one of its core features, allowing developers to insert custom logic into the request and response cycle. Middleware is divided into built-in middleware and third-party middleware, each with distinct characteristics in functionality and usage, making them suitable for different scenarios.
Built-in Middleware
Express comes with several commonly used built-in middleware that can be used directly without additional installation. These middleware typically handle basic functionalities, such as parsing request bodies or serving static files.
express.json()
express.json()
is used to parse JSON-formatted request bodies. When a client sends a request with Content-Type: application/json
, this middleware automatically converts the request body into a JavaScript object.
const express = require('express');
const app = express();
app.use(express.json());
app.post('/api/data', (req, res) => {
console.log(req.body); // Directly access the parsed JSON data
res.send('Data received');
});
app.listen(3000);
express.urlencoded()
express.urlencoded()
parses URL-encoded request bodies (typically from HTML form submissions). It uses the extended
option to determine whether to use the qs
library for parsing complex objects.
app.use(express.urlencoded({ extended: true }));
app.post('/form', (req, res) => {
console.log(req.body); // { username: 'admin', password: '123' }
res.send('Form processed');
});
express.static()
Serving static files (e.g., HTML, CSS, images) is a common requirement for web applications. express.static()
specifies the root directory for static resources:
// Serve files from the 'public' directory
app.use(express.static('public'));
// Example access: http://localhost:3000/images/logo.png
Third-party Middleware
Third-party middleware is installed via npm and extends Express's core functionality. The community provides a wide range of middleware for solving specific problems.
body-parser
Although Express 4.16+ includes similar functionality, body-parser
remains widely used. It supports parsing additional data formats:
const bodyParser = require('body-parser');
// Parse text/plain format
app.use(bodyParser.text());
app.post('/text', (req, res) => {
console.log(req.body); // Raw text string
});
morgan
morgan
is an HTTP request logger that supports multiple log formats:
const morgan = require('morgan');
app.use(morgan('dev'));
// Example output: GET /api/users 200 12.356 ms
helmet
The security middleware helmet
protects applications by setting HTTP headers:
const helmet = require('helmet');
app.use(helmet()); // Automatically enables 11 security policies
cors
When handling cross-origin requests, the cors
middleware simplifies CORS configuration:
const cors = require('cors');
app.use(cors({
origin: 'https://example.com' // Allow specific domain
}));
Custom Middleware Combinations
In real-world projects, it's common to combine multiple middleware. For example, when building an API service:
const express = require('express');
const compression = require('compression');
const rateLimit = require('express-rate-limit');
const app = express();
// Basic middleware
app.use(express.json());
app.use(helmet());
app.use(compression()); // Response compression
// Rate-limiting middleware
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100
});
app.use('/api/', limiter);
// Business routes
app.get('/api/data', (req, res) => {
res.json({ data: 'protected resource' });
});
Middleware Execution Order
The order of middleware execution is critical. The following example demonstrates the typical order for error handling:
// Logging middleware executes first
app.use(morgan('combined'));
// Business routes
app.get('/user', (req, res) => {
throw new Error('Simulated error');
});
// 404 handler
app.use((req, res) => {
res.status(404).send('Not found');
});
// Error-handling middleware (must be placed last)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Server error');
});
Performance Optimization Practices
Some middleware may impact performance and should be used carefully:
- Development-only: For example,
morgan
should use lightweight formats likecombined
in production. - Load on demand: Non-global middleware can be applied only to specific routes:
const debugMiddleware = require('debug-middleware');
app.get('/debug', debugMiddleware, (req, res) => { ... });
- Cache static files:
app.use(express.static('public', {
maxAge: '1d' // Client-side caching for 1 day
}));
Middleware Development Standards
When developing custom middleware, adhere to the following conventions:
- Must call
next()
or end the response. - Error-handling middleware requires four parameters.
- Example of an asynchronous middleware:
const authMiddleware = async (req, res, next) => {
try {
req.user = await verifyToken(req.headers.authorization);
next();
} catch (err) {
next(err); // Pass to the error handler
}
};
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:中间件的基本概念与工作原理
下一篇:自定义中间件的开发方法