From c4f1fb94a1da276bf068722266ee83ba674e7218 Mon Sep 17 00:00:00 2001 From: dekun Date: Fri, 5 Jun 2026 16:53:31 +0800 Subject: [PATCH] Fix 404 for README-based section pages in Express router MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolve directory README.html paths for nav links like 周易 and 中医宝典. Co-authored-by: Cursor --- .vitepress/config.mts | 2 +- index.md | 4 ++-- server/index.js | 46 +++++++++++++++++++++++++++++++------------ 3 files changed, 36 insertions(+), 16 deletions(-) diff --git a/.vitepress/config.mts b/.vitepress/config.mts index ebda418..30ae699 100644 --- a/.vitepress/config.mts +++ b/.vitepress/config.mts @@ -26,7 +26,7 @@ export default defineConfig({ themeConfig: { nav: [ { text: '首页', link: '/' }, - { text: '五行', link: '/金、木、水、火、土%20-%20五行/' }, + { text: '五行', link: '/金、木、水、火、土 - 五行/' }, { text: '道德经', link: '/道德经/01' }, { text: '周易', link: '/周易/' }, { text: '中医', link: '/中医宝典/' }, diff --git a/index.md b/index.md index 3824152..7cb0e06 100644 --- a/index.md +++ b/index.md @@ -11,7 +11,7 @@ hero: link: /道德经/01 - theme: alt text: 五行 - link: /金、木、水、火、土%20-%20五行/ + link: /金、木、水、火、土 - 五行/ features: - title: 道德经 @@ -30,7 +30,7 @@ features: ## 快速导航 -- [五行](/金、木、水、火、土%20-%20五行/) +- [五行](/金、木、水、火、土 - 五行/) - [抱朴子](/抱朴子/) - [鬼谷子](/鬼谷子/捭阖) - [风水](/风水/REAME) diff --git a/server/index.js b/server/index.js index 7796f6a..a026151 100644 --- a/server/index.js +++ b/server/index.js @@ -115,27 +115,47 @@ if (!fs.existsSync(distPath)) { process.exit(1) } -app.use(express.static(distPath, { index: false })) +app.use( + express.static(distPath, { + index: ['index.html', 'README.html'], + extensions: ['html'], + redirect: true, + }), +) + +function resolveHtmlPath(urlPath) { + const rel = decodeURIComponent(urlPath).replace(/^\//, '').replace(/\/$/, '') || 'index' + const candidates = [ + path.join(distPath, `${rel}.html`), + path.join(distPath, rel, 'index.html'), + path.join(distPath, rel, 'README.html'), + ] + + for (const candidate of candidates) { + if (fs.existsSync(candidate)) { + return candidate + } + } + + return null +} app.get('*', (req, res, next) => { if (req.path.includes('.')) { return next() } - const rel = req.path.replace(/^\//, '').replace(/\/$/, '') || 'index' - const candidates = [ - path.join(distPath, `${rel}.html`), - path.join(distPath, rel, 'index.html'), - path.join(distPath, '404.html'), - ] - - for (const candidate of candidates) { - if (fs.existsSync(candidate)) { - return res.sendFile(candidate) - } + const htmlPath = resolveHtmlPath(req.path) + if (htmlPath) { + return res.sendFile(htmlPath) } - return next() + const notFound = path.join(distPath, '404.html') + if (fs.existsSync(notFound)) { + return res.status(404).sendFile(notFound) + } + + return res.status(404).send('Not Found') }) app.listen(PORT, '0.0.0.0', () => {