gpt4 book ai didi

node.js - 在 Express 中,将默认文件扩展名与静态内容请求关联起来的常见方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 22:48:12 24 4
gpt4 key购买 nike

我在后端使用 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);

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

当然,我可以按照 Serve Static Files on a Dynamic Route using Express 中解释的路径从动态路由中提供文件“customers.html” 。

但是,我认为这是一种矫枉过正,此类事情应该可以通过默认文件扩展名进行简单配置,但我只是找不到如何配置。谁能告诉我吗?

最佳答案

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

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

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

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

关于node.js - 在 Express 中,将默认文件扩展名与静态内容请求关联起来的常见方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12987590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com