Files
vless-api/app.js

40 lines
965 B
JavaScript
Raw Normal View History

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}`);
});