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

相关推荐
啵啵肠11 小时前
给 AI Agent 一把求职 CLI:推荐一个面向 BOSS 直聘工作流的开源项目 boss-agent-cli
人工智能·github
谷哥的小弟11 小时前
(最新版)Git&GitHub实操图文详解教程(03)—Git工作原理
git·github·版本控制·工作原理·git工作原理
STDD12 小时前
Teeworlds / DDNet 服务器搭建:经典 2D 竞技平台游戏
服务器·游戏·github
STDD13 小时前
Alien Swarm《异星虫群》: Reactive Drop 专用服务器搭建教程
运维·服务器·github
OpenTiny社区14 小时前
2026 OpenTiny NEXT 产品调研启动!
前端·开源·github
逛逛GitHub15 小时前
推荐 8 个本周 YYDS 的 GitHub 开源项目。
github
逛逛GitHub15 小时前
这个 GitHub 上 1.6 万人点赞 AI PPT 工具,生成的 PPT 能编辑。
github
stereohomology16 小时前
ChatGPT对我首个Github开源的MCP的点评
chatgpt·开源·github
xiaoliuliu1234517 小时前
ArcGIS Pro 3.5.4专业桌面地理信息系统安装教程 Windows版:运行库+升级包+汉化补丁指南
github
_大学牲17 小时前
从零实现自己的agent第六期:Agent Team团队协作
github·agent·ai编程