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

相关推荐
鹏毓网络科技1 天前
Cursor Rules 文件配置实战:3 个隐藏参数让我每月少写 40% 样板代码
前端·github
嘻嘻仙人2 天前
Ubuntu中 git上传自己的项目和二次上传一般流程
git·github
白鲸开源2 天前
Apache SeaTunnel Zeta Engine 的 Basic Auth 是怎么工作的?
java·vue.js·github
白鲸开源2 天前
一文读懂DolphinScheduler插件机制:如何轻松扩展任务类型与数据源
java·架构·github
徐小夕3 天前
万字拆解 JitWord:企业级实时协同文档底层架构 + 大模型 AI 融合完整实践
前端·vue.js·github
码流怪侠3 天前
【GitHub】Ponytail:给 AI 编码代理植入“懒人资深开发者“灵魂的开源插件深度拆解
程序员·github·ai编程
齐翊3 天前
怎么确认 AI 看懂了你的提示词?
人工智能·github·ai编程
李小庆3 天前
Sowork AI Agent 编程助手教程 :第一章 Python环境搭建与Sowork项目克隆学习目标
github
OpenTiny社区4 天前
🎨 看完 GenUI SDK 源码我悟了!
前端·vue.js·github
千寻girling4 天前
一份不可多得的《微服务》教程
后端·面试·github