中间件(Middleware)是处理 HTTP 请求和响应的核心概念,可以处理请求的认证或者响应结果的包装等功能,例如注册登录接口不需要中间件认证,但是其他的接口都需要jwt token认证,这里就可以使用中间件分组api路由接口,实现部分接口需要认证,部分接口不需要认证。
基本中间件示例
javascript
const express = require('express');
const app = express();
// 最简单的中间件
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // 必须调用 next() 传递给下一个中间件
});
// 路由处理
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000);
应用级别中间件
javascript
// 应用到所有路由
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
// 应用到特定路径
app.use('/user', (req, res, next) => {
console.log('User middleware');
next();
});
// 多个中间件函数
app.use('/api',
(req, res, next) => {
console.log('First middleware');
next();
},
(req, res, next) => {
console.log('Second middleware');
next();
}
);
路由级别中间件
javascript
const router = express.Router();
router.use((req, res, next) => {
console.log('Router middleware');
next();
});
router.get('/', (req, res) => {
res.send('Router home');
});
app.use('/admin', router);
如果需要部分接口需要认证,部分接口不需要token认证,就可以使用路由中间件将他们分开,例如认证中间件的代码:
javascript
import { Request, Response, NextFunction } from 'express';
import { env } from 'cloudflare:workers';
import { verifyJWT } from '../utils/auth';
export async function authMiddleware(req: Request, res: Response, next: NextFunction) {
const auth = req.headers.authorization;
if (!auth || !auth.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
// get token from header
const token = auth.slice(7);
try {
const payload = await verifyJWT(token, env.JWT_SECRET);
// middleware
req.user = {
id: payload.id,
email: payload.email,
};
// next middleware
next();
} catch {
return res.status(401).json({ error: 'Invalid token' });
}
}
将路由分开为注册登录和其他的路由文件:

在需要认证的路由中使用认证中间件:

这样做的话,这个路由文件中的路由就都需要经过token认证才可以访问:
