app.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import express from "express";
  2. import fileUpload from "express-fileupload";
  3. import bodyParser from "body-parser";
  4. import cors from "cors";
  5. // import authors from "./router/authors/index.js";
  6. // import authorsLogin from "./router/authors/login.js";
  7. // import books from "./router/books/index.js";
  8. // import files from "./router/files/index.js";
  9. // import record from "./router/record/index.js";
  10. // import moreRecord from "./router/record/more.js";
  11. // import types from "./router/types/index.js";
  12. import epub from "./router/epub/index.js";
  13. import { generateToken, verifyToken } from "#utils";
  14. import logger from '#logger'
  15. const port = 3000;
  16. const app = express();
  17. const json = express.json({ type: "*/json" });
  18. // 全局启用 CORS
  19. const corsOptions = {
  20. origin: "http://localhost:3032", // 仅允许这个来源
  21. methods: ["GET", "POST", "PUT", "DELETE"], // 允许的 HTTP 方法
  22. allowedHeaders: ["Content-Type", "Authorization"], // 允许的头部
  23. };
  24. app.use(cors(corsOptions));
  25. app.use(fileUpload());
  26. app.use(json);
  27. app.use(bodyParser.urlencoded({ extended: false }));
  28. // Helper function to validate referer
  29. function isValidReferer(referer) {
  30. return (
  31. referer.indexOf("zs_interval") > -1 && referer.indexOf("/api/v1/files") > -1 || referer.indexOf('api_files_') > -1
  32. );
  33. }
  34. // Helper function to extract `file_id` from referer
  35. function extractFileId(referer) {
  36. const match = referer.match(/api_files_([^/]+)/); // 正则匹配 `file_id`
  37. return match ? match[1] : null;
  38. }
  39. // middleware that is specific to this router
  40. app.use(async function timeLog(req, res, next) {
  41. if (isValidReferer(req.url)) {
  42. const fileId = extractFileId(req.url);
  43. if (fileId) {
  44. return res.redirect(`/api/v1/files/${fileId}`);
  45. } else {
  46. logger.error("File ID not found in referer");
  47. }
  48. }
  49. next();
  50. });
  51. // 静态文件目录,添加前缀路径 /static
  52. // app.use("/static", express.static("public"));
  53. app.get("/", (req, res) => {
  54. res.send("Hello World! " + req.url);
  55. });
  56. // app.use("/api/v1/login", authors);
  57. // app.use("/api/v1/files", files);
  58. app.use("/api/v1/epub", epub);
  59. // app.use("/api/v1/*", verifyToken); // 注册token验证中间件
  60. // app.use("/api/v1/auth", authorsLogin);
  61. // app.use("/api/v1/books", books);
  62. // app.use("/api/v1/record", record);
  63. // app.use("/api/v1/more_record", moreRecord);
  64. // app.use("/api/v1/types", types);
  65. app.listen(port, () => {
  66. console.log(`Example app listening on port ${port}`)
  67. logger.info(`Example app listening on port ${port}`)
  68. });