From a7f6d0738171dbcdb530acecd91867a3079b04ac Mon Sep 17 00:00:00 2001 From: Julian Kniephoff Date: Tue, 14 May 2024 09:32:37 +0200 Subject: [PATCH] Further simplify the static file server This avoids having to poorly reimplement `express.static` using some internal request rewriting logic. --- staticServer.js | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/staticServer.js b/staticServer.js index 352b4c9b36..59dcafc16b 100644 --- a/staticServer.js +++ b/staticServer.js @@ -2,24 +2,26 @@ const path = require("path"); const express = require("express"); const app = express(); -const port = process.env.PORT || 5000; -app.get("/*", express.static(path.join(__dirname, "test/app/GET"))); +for (const method of ["post", "put", "delete"]) { + app[method]("/*", (req, res, next) => { + setTimeout(next, 1000); + }); +} app.post("/*", (req, res, next) => { res.status(201); next(); }); -const serveStatic = (req, res) => { - const filePath = path.join(__dirname, "test/app", req.method.toUpperCase(), req.url); - setTimeout(() => { - res.sendFile(filePath); - }, 1000); -}; - -for (const method of ["put", "post", "delete"]) { - app[method]("/*", serveStatic); -} +app.use("/", [ + (req, res, next) => { + req.url = `/${req.method}${req.url}`; + req.method = "GET"; + next(); + }, + express.static(path.join(__dirname, "test/app")) +]); +const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Listing on port ${port}`));