server.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import express from "express";
  2. import { serverConfig } from "./config.js";
  3. import { logger } from "./middleware/logger.js";
  4. import { errorHandler } from "./middleware/errorHandler.js";
  5. import exampleRoutes from "./routes/exampleRoutes.js";
  6. import chartRoutes from "./routes/chartRoutes.js";
  7. import path from "path";
  8. import { fileURLToPath } from "url";
  9. const __filename = fileURLToPath(import.meta.url);
  10. const __dirname = path.dirname(__filename);
  11. const app = express();
  12. // 中间件
  13. app.use(express.json());
  14. app.use(logger);
  15. // 静态文件服务
  16. app.use("/images", express.static(path.join(process.cwd(), "src", "images")));
  17. app.use("/js", express.static(path.join(process.cwd(), "src", "public", "js")));
  18. app.use(
  19. "/testData.json",
  20. express.static(path.join(process.cwd(), "src", "testData.json"))
  21. );
  22. // 路由
  23. app.use("/api/examples", exampleRoutes);
  24. app.use("/api/charts", chartRoutes);
  25. // 错误处理
  26. app.use(errorHandler);
  27. export const startServer = () => {
  28. app.listen(serverConfig.port, serverConfig.host, () => {
  29. console.log(
  30. `Server is running on http://${serverConfig.host}:${serverConfig.port}`
  31. );
  32. });
  33. };
  34. export default app;