12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- import express from "express";
- import fileUpload from "express-fileupload";
- import bodyParser from "body-parser";
- import cors from "cors";
- import authors from "./router/authors/index.js";
- import authorsLogin from "./router/authors/login.js";
- import books from "./router/books/index.js";
- import files from "./router/files/index.js";
- import record from "./router/record/index.js";
- import moreRecord from "./router/record/more.js";
- import types from "./router/types/index.js";
- import epub from "./router/epub/index.js";
- import { generateToken, verifyToken } from "#utils";
- const port = 3000;
- const app = express();
- const json = express.json({ type: "*/json" });
- // 全局启用 CORS
- const corsOptions = {
- origin: "http://localhost:3032", // 仅允许这个来源
- methods: ["GET", "POST", "PUT", "DELETE"], // 允许的 HTTP 方法
- allowedHeaders: ["Content-Type", "Authorization"], // 允许的头部
- };
- app.use(cors(corsOptions));
- app.use(fileUpload());
- app.use(json);
- app.use(bodyParser.urlencoded({ extended: false }));
- // Helper function to validate referer
- function isValidReferer(referer) {
- return (
- referer.indexOf("zs_interval") > -1 && referer.indexOf("/api/v1/files") > -1 || referer.indexOf('api_files_') > -1
- );
- }
- // Helper function to extract `file_id` from referer
- function extractFileId(referer) {
- const match = referer.match(/api_files_([^/]+)/); // 正则匹配 `file_id`
- return match ? match[1] : null;
- }
- // middleware that is specific to this router
- app.use(async function timeLog(req, res, next) {
- if (isValidReferer(req.url)) {
- const fileId = extractFileId(req.url);
- if (fileId) {
- return res.redirect(`/api/v1/files/${fileId}`);
- } else {
- console.error("File ID not found in referer");
- }
- }
- next();
- });
- // 静态文件目录,添加前缀路径 /static
- app.use("/static", express.static("public"));
- app.get("/", (req, res) => {
- res.send("Hello World! " + req.url);
- });
- app.use("/api/v1/login", authors);
- app.use("/api/v1/files", files);
- app.use("/api/v1/epub", epub);
- app.use("/api/v1/*", verifyToken); // 注册token验证中间件
- app.use("/api/v1/auth", authorsLogin);
- app.use("/api/v1/books", books);
- app.use("/api/v1/record", record);
- app.use("/api/v1/more_record", moreRecord);
- app.use("/api/v1/types", types);
- app.listen(port, () => {
- console.log(`Example app listening on port ${port}`);
- });
|