【问题标题】:Serving static files from Express without extension, issue with sub directories with same name a file从没有扩展名的 Express 提供静态文件,与文件同名的子目录问题
【发布时间】:2020-05-12 15:25:44
【问题描述】:

这里的目标是为我的静态网站(使用 nuxtjs 生成)提供带有 url 而没有尾部斜杠的服务。

我想为foo.html 提供网址/foo 为此,我使用带有扩展选项的 express static

app.use(express.static(__dirname + '/public', { extensions: 'html' }))

这工作正常除非 html 文件与文件夹具有相同的名称。 让我们考虑一下这个文件树:

foo.html
bar.html
bar/baz.html

/foo 将服务于foo.html

/bar/baz 将服务于baz.html

但是/bar 会重定向到/bar/

我试图以这种方式停用重定向选项:

app.use(express.static(__dirname + '/public', { extensions: 'html', redirect: false }))

现在/bar 不再重定向,但文件bar.html 仍未提供服务!

Express 只是移动到 next()

我能够在其他路由之后添加这个 bar.html 服务:

app.use(function(req, res, next) {
    var file = __dirname + '/public' + req.path + '.html'
    fs.exists(file, function(exists) {
        if (exists) res.sendFile(file)
        else next()
    })
})

但我觉得这不应该是正确的做法,我应该能够使用静态文件提供所有文件。

【问题讨论】:

  • 我不明白你到底想做什么,但是当express.static() 发现/foo 匹配静态文件层次结构中的foo 目录时,它会在该目录中查找对于index.html 文件,如果找到,它将提供服务。也许你可以用它来解决你的问题。
  • 准确地说是:express.static() 发现/foo 匹配静态文件层次结构中的foo 目录,它将重定向到/foo/,然后/foo/ 请求将被处理使用/foo/index.html,但由于该重定向网址将是/foo/,并带有斜杠。问题是我的网站是使用 nuxt js 生成的,它作为单页应用程序工作,具有可见的 href,没有尾部斜杠,因此看起来我的所有链接都指向 301 重定向。我的老板认为这很糟糕(因为他的 SEO 工具会显示一些红色)。
  • 您有多少个这些目录 URL?您可以为他们定义手动路线,让他们完全按照您的意愿行事。

标签: node.js express


【解决方案1】:

从 Express 4.8.0 开始,您可以使用 res.sendFile 作为 express.static 的替代方案。它使用相同的支持代码,并支持相同的功能,例如 HTTP 缓存支持、内容类型标头等。

const root = path.join(__dirname, '/public');
app.use((req, res, next) => {
  const file = req.url + ".html";
  fs.exists(path.join(root, file), (exists) =>
    exists ? res.sendFile(file, {root}) : next()
  );
});

【讨论】: