app.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import Koa from 'koa';
  2. import bodyParser from 'koa-bodyparser';
  3. import serve from 'koa-static';
  4. import path from 'path';
  5. import { fileURLToPath } from 'url';
  6. import config from './config/index.js';
  7. import mpsRouter from './api/mps/routes.js';
  8. import phonicsRouter from './api/phonics/routes.js';
  9. import commonRouter from './api/common/routes.js';
  10. import { decryptUrlMiddle } from './util/crypto/index.js';
  11. import { stringUtils } from './util/stringClass.js';
  12. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  13. const app = new Koa();
  14. // 使用中间件
  15. app.use(bodyParser());
  16. // 静态文件服务
  17. app.use(serve(__dirname + '/../public'));
  18. // 错误处理
  19. app.use(async (ctx, next) => {
  20. try {
  21. await next();
  22. } catch (err) {
  23. ctx.status = err.status || 500;
  24. ctx.body = { error: err.message };
  25. ctx.app.emit('error', err, ctx);
  26. }
  27. });
  28. app.use(decryptUrlMiddle());
  29. // 注册路由
  30. app.use(commonRouter.routes());
  31. app.use(commonRouter.allowedMethods());
  32. app.use(mpsRouter.routes());
  33. app.use(mpsRouter.allowedMethods());
  34. app.use(phonicsRouter.routes());
  35. app.use(phonicsRouter.allowedMethods());
  36. // 启动服务器
  37. app.listen(config.port, () => {
  38. console.log('Server IP:', stringUtils.GetServerIP());
  39. console.log(`Server running on port ${config.port}`);
  40. });