app.js 2.3 KB

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