app.js 2.5 KB

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