app.js 2.2 KB

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