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:
40
app.js
Normal file
40
app.js
Normal 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}`);
|
||||
});
|
||||
Reference in New Issue
Block a user