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

相关推荐
xuhe21 分钟前
[全流程详细教程]Docker部署ClawBot, 使用GLM4.7, 接入TG Bot实现私人助理. 解决Docker Openclaw Permission Denied问题
linux·docker·ai·github·tldr
宇宙帅猴35 分钟前
GitHub 私有仓库认证完整指南:告别密码错误,使用 PAT 令牌
github
前端市界3 小时前
用 React 手搓一个 3D 翻页书籍组件,呼吸海浪式翻页,交互体验带感!
前端·架构·github
happyprince3 小时前
2026年02月07日热门github项目
github
CoderJia程序员甲4 小时前
GitHub 热榜项目 - 日榜(2026-02-06)
人工智能·ai·大模型·github·ai教程
荔枝吻6 小时前
忘记服务器密码,在Xshell7中查看已保存密码
运维·服务器·github
tod1138 小时前
TCP全连接队列与tcpdump抓包
网络·网络协议·tcp/ip·github·tcpdump
Luck_ff08109 小时前
百度指数数据采集与可视化平台 BaiduIndexHunter
github·开源软件
阿里嘎多学长9 小时前
2026-02-03 GitHub 热点项目精选
开发语言·程序员·github·代码托管
子兮曰16 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github