From 906c3fa856869804825b40fa30abf1abc1ee208e Mon Sep 17 00:00:00 2001 From: Haider Ali <73281382+haider53e@users.noreply.github.com> Date: Fri, 17 Nov 2023 20:24:42 +0500 Subject: [PATCH] Mount HTML serving middlewares at config.base (#91) * add ignore base option * Vite Index Middleware should only handle GET requests * Use base directly instead of introducing another config option * Specified base must be included in the page address * Add optional base parameter in the testCase --- src/main.ts | 11 +++++++---- tests/templates.test.ts | 13 ++++++------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/src/main.ts b/src/main.ts index 3f73d19..5e9d07b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -213,7 +213,9 @@ async function injectViteIndexMiddleware( ) { const config = await getViteConfig(); - app.get("/*", async (req, res, next) => { + app.use(config.base, async (req, res, next) => { + if (req.method !== "GET") return next(); + if (isIgnoredPath(req.path, req)) return next(); if (isStaticFilePath(req.path)) next(); @@ -230,11 +232,12 @@ async function injectViteIndexMiddleware( async function injectIndexMiddleware(app: core.Express) { const distPath = await getDistPath(); + const config = await getViteConfig(); - app.use("*", (req, res, next) => { - if (isIgnoredPath(req.baseUrl, req)) return next(); + app.use(config.base, (req, res, next) => { + if (isIgnoredPath(req.path, req)) return next(); - const indexPath = findClosestIndexToRoot(req.originalUrl, distPath); + const indexPath = findClosestIndexToRoot(req.path, distPath); if (indexPath === undefined) return next(); const html = fs.readFileSync(indexPath, "utf8"); diff --git a/tests/templates.test.ts b/tests/templates.test.ts index 07ebc2b..50a43ea 100644 --- a/tests/templates.test.ts +++ b/tests/templates.test.ts @@ -46,25 +46,24 @@ for (const template of templates) { test(`Template "${template}" with custom inline config`, async (done) => { process.chdir(`create-vite-express/templates/${template}`); + const base = "/admin"; + ViteExpress.config({ - inlineViteConfig: { - base: "/admin", - build: { outDir: "out" }, - }, + inlineViteConfig: { base, build: { outDir: "out" } }, }); await ViteExpress.build(); - await testCase(template, done); + await testCase(template, done, base); }); } -const testCase = async (template: string, done: () => void) => { +const testCase = async (template: string, done: () => void, base = "/") => { const server = ViteExpress.listen(express(), 3000, () => { const browser = puppeteer.launch(); browser.then(async (browser) => { const page = await browser.newPage(); - await page.goto("http://localhost:3000"); + await page.goto(`http://localhost:3000${base}`); it("test set up");