node.js实现分页和jwt鉴权机制

const express = require('express');

const jwt = require('jsonwebtoken');

const app = express();

// 模拟数据库

const db = {

users: [

{ id: 1, username: 'user1', email: 'user1@example.com' },

// ...更多用户

],

// ...其他数据模型

};

// 应用中间件

app.use(express.json()); // 解析请求体中的JSON数据

// JWT密钥

const secretKey = 'your-secret-key';

// 鉴权中间件

app.use((req, res, next) => {

const authHeader = req.headers'authorization';

const token = authHeader && authHeader.split(' ')1;

if (token == null) return res.sendStatus(401);

jwt.verify(token, secretKey, (err, user) => {

if (err) return res.sendStatus(403);

req.user = user;

next();

});

});

// 分页处理中间件

app.use((req, res, next) => {

const page = req.query.page ? parseInt(req.query.page) : 1;

const limit = req.query.limit ? parseInt(req.query.limit) : 10;

const startIndex = (page - 1) * limit;

const endIndex = startIndex + limit;

req.pagination = { page, limit, startIndex, endIndex };

next();

});

// 获取用户列表的API

app.get('/api/users', (req, res) => {

const { startIndex, endIndex } = req.pagination;

const users = db.users.slice(startIndex, endIndex);

res.json(users);

});

// 用户登录API,生成JWT

app.post('/api/login', (req, res) => {

const { username, password } = req.body;

// 这里应该是用户验证的逻辑,假设用户名和密码都是'user1'

if (username === 'user1' && password === 'user1') {

const token = jwt.sign({ userId: 1 }, secretKey, { expiresIn: '1h' });

res.json({ token });

} else {

res.status(401).send('Invalid username or password');

}

});

// 启动服务器

const PORT = 3000;

app.listen(PORT, () => {

console.log(`Server is running on port ${PORT}`);

});

这段代码实现了一个简单的Node.js服务器,包括JWT鉴权和分页处理的功能。在实际应用中,你需要替换掉硬编码的用户信息和密钥,并且添加用户注册接口,以及更复杂的鉴权逻辑和数据库查询。

相关推荐
蚕豆糯米饭15 小时前
Github Copilot 研发效能提升实战指南
ai·github·copilot·ai编程
AlfredZhao17 小时前
GitHub 克隆他人私有仓库:从授权到下载
github
智能制造产品经理代码提升18 小时前
Windows Git 多 GitHub 账号切换(GCM 管理凭据,不覆盖原有账号)
github
Wang's Blog19 小时前
Java框架快速入门: Spring Security+OAuth2之核心角色与授权流程
java·spring·github
dong_junshuai19 小时前
每天一个开源项目#100 OpenCodeReview:2.6万星的低噪声AI审查器
程序员·开源·github
峰向AI19 小时前
还在用 Ableton?这个 3.5K Star 的免费音序器,让你在手机上写微分音音乐
github
SL_staff20 小时前
战略落地的最后一公里:从目标到个人日历的自动化链路实现
java·github·全栈
凌奕20 小时前
OpenCodeReview 架构拆解:AI Code Review 为什么不能只是 Git Diff + LLM?
llm·github·agent
m4Rk_1 天前
【论文阅读】Agent 记忆机制(70):RecMem——只在记忆反复出现时才调用 LLM 做巩固
论文阅读·人工智能·学习·开源·github
u1301301 天前
GitHub 热榜项目:日榜(2026-09-14)
人工智能·github