在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);

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

当然,我可以通过遵循使用Express在动态路线上的静态文件中解释的路径,从动态路线中使用" Customer.html"。

但是,我认为这是一个过大的杀伤力,这种事情应该简单地通过默认文件扩展名进行配置,但是我只是找不到方法。谁能告诉我?

express statation基于服务静态,因此您可以在Extensions属性设置的选项对象中传递。就您的示例而言,以下是可行的:

app.use(express.static(webRootDir, {'extensions': ['html']}));

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

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

最新更新