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鉴权和分页处理的功能。在实际应用中,你需要替换掉硬编码的用户信息和密钥,并且添加用户注册接口,以及更复杂的鉴权逻辑和数据库查询。

相关推荐
Hy行者勇哥1 小时前
MobaXterm 高效运维实战:从入门到进阶的 Linux 运维 “瑞士军刀” 用法
linux·运维·github
qq7422349846 小时前
VitePress静态网站从零搭建到GitHub Pages部署一站式指南和DeepWiki:AI 驱动的下一代代码知识平台
人工智能·python·vue·github·vitepress·wiki
用户219916797039117 小时前
.Net通过EFCore和仓储模式实现统一数据权限管控并且相关权限配置动态生成
后端·github
DKNG20 小时前
【Windows Host】 hosts配置增加访问github流畅度
人工智能·git·github
逛逛GitHub21 小时前
我把公众号文章导入了腾讯 ima,可以对话找开源项目了。
前端·github
徐小夕1 天前
10k Star 的开源 AI 记忆引擎:6 行代码,用图谱+向量打造永不遗忘的 AI
前端·后端·github
慕容长风1 天前
github使用指南
github
WYiQIU1 天前
从今天开始备战1月中旬的前端寒假实习需要准备什么?(飞书+github+源码+题库含答案)
前端·javascript·面试·职场和发展·前端框架·github·飞书
一念一花一世界1 天前
Arbess从基础到实践(20) - 集成GitHub+SonarQube实现Java项目自动化部署
java·github·cicd·arbess
CoderJia程序员甲1 天前
GitHub 热榜项目 - 日榜(2025-12-17)
ai·开源·大模型·github·ai教程