feat(路由): 添加路由加载器和配置实现自动化路由注册
重构服务器路由注册逻辑,将手动路由注册替换为基于配置的自动加载 新增路由加载器工具和路由配置文件,支持动态加载和错误处理
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
const path = require('path');
|
||||
const routesConfig = require('../config/routes');
|
||||
|
||||
function loadRoutes(app) {
|
||||
const routesDir = path.join(__dirname, '../routes');
|
||||
|
||||
routesConfig.forEach((routeConfig) => {
|
||||
try {
|
||||
const routerPath = path.join(routesDir, routeConfig.file);
|
||||
const router = require(routerPath);
|
||||
|
||||
if (typeof router === 'function') {
|
||||
app.use(routeConfig.path, router);
|
||||
console.log(`路由已加载: ${routeConfig.path} -> ${routeConfig.file}`);
|
||||
} else {
|
||||
console.warn(`警告: ${routeConfig.file} 没有导出有效的 Express 路由器`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`加载路由失败: ${routeConfig.file}`, error.message);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = loadRoutes;
|
||||
Reference in New Issue
Block a user