在 express 中,将默认文件扩展名与静态内容请求相关联的常用方法是什么?

mar*_*ark 2 node.js express

我在后端使用 Express (v3),它还提供我的静态内容,如下所示:

app.use(allowCrossDomain);
app.use(disableETag);
app.use(app.router);
app.use(express["static"](webRootDir));
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.set('view engine', 'html');
app.set('views', webRootDir);
app.engine("html", handlebarsEngine);
Run Code Online (Sandbox Code Playgroud)

因此,对“/customers.html”的请求由 express.static中间件提供服务。但是,请求“/customers”不起作用,因为没有“customers”文件,也没有这样的动态内容路由。

当然,我可以按照使用 Express 在动态路由上提供静态文件中解释的路径从动态路由提供文件“customers.html” 。

但是,我认为这是一种矫枉过正,这种事情应该可以通过默认文件扩展名简单地配置,但我找不到如何。谁能给我看看?

Bra*_*ver 6

express static 是基于 serve-static 的,因此您可以传入一个带有扩展属性集的选项对象。对于您的示例,以下内容将起作用:

app.use(express.static(webRootDir, {'extensions': ['html']}));
Run Code Online (Sandbox Code Playgroud)

这会设置 express 以便如果找不到文件,例如/customers它会尝试将每个扩展名附加到路径中,因此在您的情况下/customers.html

请参阅https://github.com/expressjs/serve-static#serve-files-with-vanilla-nodejs-http-server 上的文档