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

const express = require('express');

const jwt = require('jsonwebtoken');

const app = express();

// 模拟数据库

const db = {

users: [

{ id: 1, username: 'user1', email: '[email protected]' },

// ...更多用户

],

// ...其他数据模型

};

// 应用中间件

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

相关推荐
opentrending4 小时前
Github 热点项目 Cursor开源代替,AI代理+可视化编程!支持本地部署的隐私友好型开发神器。
人工智能·开源·github
刃神太酷啦1 天前
C++入门(下)--《Hello C++ World!》(2)(C/C++)
java·c语言·c++·git·算法·github
正经码农3 天前
团队协作的润滑剂——GitHub与协作流程
github
北上ing3 天前
Github上如何准确地搜索开源项目
开源·github
ElenaYu3 天前
使用Homebrew下载配置git和连接GitHub(Mac版)
git·macos·github
CoderJia程序员甲3 天前
RAG_Techniques:探索GitHub热门RAG技术开源项目
ai·llm·github·ai教程·rag技术
孔令飞4 天前
如何从GitHub上调研优秀的开源项目,并魔改应用于工作中?
ai·云原生·golang·kubernetes·开源·github
qianmoQ4 天前
GitHub 趋势日报 (2025年05月03日)
github
露临霜4 天前
vue实现AI问答Markdown打字机效果
前端·javascript·vue.js·ai·github
z5z3c4 天前
如何用git将项目上传到github
git·github