Fix 404 for README-based section pages in Express router

Resolve directory README.html paths for nav links like 周易 and 中医宝典.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-06-05 16:53:31 +08:00
parent 68d816b3f3
commit c4f1fb94a1
3 changed files with 36 additions and 16 deletions
+33 -13
View File
@@ -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', () => {