Express.js中间件Middleware是处理 HTTP 请求和响应以及jwt token认证

中间件(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认证才可以访问:

相关推荐
海市公约22 分钟前
微服务Token认证从登录到鉴权的完整执行链路
微服务·中间件·权限控制·token认证·分布式安全
Trouvaille ~26 分钟前
【Redis篇】为什么需要 Redis:从单机到分布式的架构演进之路
数据库·redis·分布式·缓存·中间件·架构·后端开发
lolo大魔王30 分钟前
Go 语言 HTTP 协议与 RESTful API 实训全解(理论 + 实战 + 规范)
http·golang·restful
marsh020640 分钟前
51 openclaw自定义中间件:解决特定业务需求的扩展方案
中间件·ai编程
云游牧者42 分钟前
K8S-Ingress流量治理全解-Traefik从入门到实战完全指南
云原生·中间件·容器·kubernetes·ingress·traefik
长谷深风1112 小时前
HTTP请求全过程解析【个人八股】
网络·网络协议·http·多线程下载·tcp 连接·请求报文、响应报文·网络请求流程
艾莉丝努力练剑2 小时前
【Linux网络】Linux 网络编程:HTTP(四)从手写服务器到生产级 Nginx 与 cpp-httplib 实战
linux·运维·服务器·网络·c++·nginx·http
艾莉丝努力练剑2 小时前
【Linux网络】Linux 网络编程:HTTP(三)HTTP 协议原理
linux·运维·服务器·网络·c++·http
handler011 天前
【Linux 网络】一文读懂 HTTP 协议
linux·c语言·网络·c++·笔记·网络协议·http
绝知此事1 天前
【计算机网络系列 2/3】HTTP协议深度解析:从HTTP1.0到HTTP3.0的演进之路
网络协议·计算机网络·http