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

相关推荐
华科大胡子9 小时前
GitHub Actions 自动化运维实战:从入门到企业级应用
github
小小龙学IT10 小时前
Taskflow:用一张“任务图“玩转现代 C++ 并行编程开源项
c++·开源·github
大模型丫丫10 小时前
GitHub Actions 自动化运维实战:从 CI/CD 到云端部署
运维·自动化·github
m4Rk_11 小时前
【论文阅读】Agent 记忆机制(31):MemAgent——通过强化学习让固定长度记忆处理百万级长文本
论文阅读·人工智能·学习·开源·github
笨鸟先飞,勤能补拙11 小时前
密码学深度指南 — SecOps 工程师实战手册
人工智能·vscode·python·安全·github·密码学·visual studio
TunerT_TQ11 小时前
Valhalla 静态工程审阅 #004|MoonshotAI MoonEP 源码证据驱动评测【大厂开源基础设施特辑】
架构·github
0xR3lativ1ty1 天前
每日GitHub trending精选
github
带娃的IT创业者1 天前
GitHub 热门项目解析:当 AI 编码助手遭遇“上下文爆炸”
人工智能·github·代码优化·ai编程助手·上下文窗口·上下文压缩
白鲸开源1 天前
Apache SeaTunnel 提交一个任务都经过了什么?
大数据·开源·github
dong_junshuai1 天前
每天一个开源项目#60 TencentDB Agent Memory:1.4万星的团队记忆中枢
github·腾讯