app.js 2.3 KB

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