feat: 初始化项目并添加 JWT 认证

- 创建 .gitignore 文件,排除环境变量和节点模块
- 新增 app.js 文件,实现基本的 Koa 应用和 JWT 认证逻辑
- 添加 package.json 文件,定义项目依赖和启动脚本

安装依赖:
- dotenv:用于加载环境变量
- jsonwebtoken:用于生成和验证 JWT 令牌
- koa:Koa 应用框架
- koa-jwt:Koa 的 JWT 中间件
- koa-router:Koa 的路由中间件
This commit is contained in:
aixianling
2025-02-24 17:41:40 +08:00
commit 4f6d44ec49
3 changed files with 61 additions and 0 deletions

40
app.js Normal file
View File

@@ -0,0 +1,40 @@
require('dotenv').config(); // 在文件最顶部加载环境变量
const Koa = require('koa');
const Router = require('koa-router');
const jwt = require('jsonwebtoken');
const koaJwt = require('koa-jwt');
const app = new Koa();
const router = new Router();
// 公开路由
router.get('/public', ctx => {
ctx.body = 'Public content';
});
// 登录路由
router.post('/login', ctx => {
const user = { id: 1, username: 'admin' };
const token = jwt.sign(user, process.env.JWT_SECRET, { expiresIn: '1h' });
ctx.body = { token };
});
// JWT中间件
app.use(koaJwt({
secret: process.env.JWT_SECRET
}).unless({
path: [/^\/public/]
}));
// 受保护路由
router.get('/protected', ctx => {
ctx.body = `Protected content for ${ctx.state.user.username}`;
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(process.env.PORT || 3000, () => {
console.log(`Server running on http://localhost:${process.env.PORT || 3000}`);
});