server.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import dotenv from "dotenv";
  2. // 加载 .env 文件中的环境变量
  3. dotenv.config();
  4. import express from "express";
  5. import { serverConfig } from "./config.js";
  6. import { logger } from "./middleware/logger.js";
  7. import { errorHandler } from "./middleware/errorHandler.js";
  8. import exampleRoutes from "./routes/exampleRoutes.js";
  9. import chartRoutes from "./routes/chartRoutes.js";
  10. import path from "path";
  11. import { fileURLToPath } from "url";
  12. // 引入 cors 模块
  13. import cors from "cors";
  14. const __filename = fileURLToPath(import.meta.url);
  15. const __dirname = path.dirname(__filename);
  16. const app = express();
  17. // 使用 cors 中间件
  18. app.use(cors());
  19. // 中间件
  20. app.use(express.json({ limit: "100mb" }));
  21. app.use(logger);
  22. // 静态文件服务
  23. app.use("/images", express.static(path.join(process.cwd(), "src", "images")));
  24. app.use("/js", express.static(path.join(process.cwd(), "src", "public", "js")));
  25. app.use(
  26. "/testData.json",
  27. express.static(path.join(process.cwd(), "src", "testData.json"))
  28. );
  29. // 路由
  30. app.use("/examples", exampleRoutes);
  31. app.use("/chartServer/charts", chartRoutes);
  32. // 错误处理
  33. app.use(errorHandler);
  34. export const startServer = () => {
  35. app.listen(serverConfig.port, serverConfig.host, () => {
  36. console.log(
  37. `Server is running on http://${serverConfig.host}:${serverConfig.port}`
  38. );
  39. });
  40. };
  41. export default app;