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

相关推荐
liulovesong14 小时前
2024/06/21/第三天
http·echarts
岁岁种桃花儿20 小时前
Kafka从入门到上天系列第一篇:kafka的安装和启动
大数据·中间件·kafka
win x1 天前
深入理解HTTPS协议加密流程
网络协议·http·https
仙俊红1 天前
从 Filter / Interceptor 到 HTTPS
网络协议·http·https
liann1191 天前
3.1_网络——基础
网络·安全·web安全·http·网络安全
三水不滴2 天前
计算机网络核心网络模型
经验分享·笔记·tcp/ip·计算机网络·http·https
SunflowerCoder2 天前
基于插件化 + Scriban 模板引擎的高效 HTTP 协议中心设计
http·c#
Remember_9932 天前
MySQL 索引详解:从原理到实战优化
java·数据库·mysql·spring·http·adb·面试
波波0072 天前
每日一题:中间件是如何工作的?
中间件·.net·面试题
玄同7652 天前
LangChain 1.0 框架全面解析:从架构到实践
人工智能·深度学习·自然语言处理·中间件·架构·langchain·rag