Compare commits

...

3 Commits

Author SHA1 Message Date
aixianling
628a6fee80 refactor(api): 重命名示例 API 文件并简化代码
- 将 api/example.js 重命名为 api/addClient.js
- 删除多余的空行和注释
2025-02-25 17:53:36 +08:00
aixianling
448acfc26a feat(app): 添加 API 路由前缀并优化用户信息处理
- 在 API 路由中添加 "/api" 前缀,实现 URL 优化
- 修复用户信息存储逻辑,确保正确信息保存在上下文中
- 更新第三方 Token 验证函数,增加用户名字段
2025-02-25 17:49:54 +08:00
aixianling
b895f8f247 refactor(app): 重构应用并添加开发脚本
- 移除了登录路由
- 添加了 nodemon 开发脚本
- 引入了 nodemon 依赖
- 在 verifyThirdPartyToken 中添加了日志输出
2025-02-25 17:40:08 +08:00
4 changed files with 12 additions and 16 deletions

View File

@@ -1,5 +1,6 @@
// api/example.js
module.exports = (ctx) => {
ctx.body = {
message: 'Example POST API',
data: ctx.request.body

11
app.js
View File

@@ -18,7 +18,7 @@ const loadAPIRoutes = () => {
files.forEach((file) => {
if (file.endsWith(".js") && file !== "index.js") {
const routePath = `/${file.replace(".js", "")}`;
const routePath = `/api/${file.replace(".js", "")}`;
const handler = require(path.join(apiDir, file));
router.post(routePath, async (ctx) => {
@@ -33,13 +33,6 @@ 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 };
});
// 自定义中间件解析并验证第三方Token
app.use(async (ctx, next) => {
const authHeader = ctx.headers.authorization;
@@ -49,7 +42,7 @@ app.use(async (ctx, next) => {
// 这里假设第三方Token可以通过某种方式验证并转换为JWT Token
const decoded = verifyThirdPartyToken(thirdPartyToken); // 假设有一个验证函数
const jwtToken = jwt.sign(decoded, process.env.JWT_SECRET, { expiresIn: "1h" });
ctx.state.user = user; // 将用户信息存储在ctx.state中
ctx.state.user = decoded; // 将用户信息存储在ctx.state中
ctx.headers.authorization = `Bearer ${jwtToken}`; // 替换为JWT Token
} catch (err) {
ctx.throw(401, 'Invalid third-party token');

View File

@@ -1,3 +1,3 @@
module.exports = token=>{
return {token}
}
module.exports = (token) => {
return { token, username: token };
};

View File

@@ -4,7 +4,8 @@
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js"
"start": "node app.js",
"dev": "nodemon app.js"
},
"author": "kubbo",
"license": "ISC",
@@ -14,6 +15,7 @@
"koa": "^2.15.4",
"koa-bodyparser": "^4.4.1",
"koa-jwt": "^4.0.4",
"koa-router": "^13.0.1"
"koa-router": "^13.0.1",
"nodemon": "^3.0.2"
}
}
}