在表达方式中,将默认文件扩展名与静态内容请求相关联的常用方法是什么? [英] In express what is the common way to associate a default file extension with static content requests?

查看:46
本文介绍了在表达方式中,将默认文件扩展名与静态内容请求相关联的常用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use Express (v3) on my backend and it also serves my static content, like this:

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"的请求.但是,请求"/customers"不起作用,因为没有"customers"文件,也没有这样的动态内容路由.

So, a request for "/customers.html" is served by the express.static middleware. However, requesting "/customers" does not work, because there is no "customers" file and there is no such dynamic content route either.

当然,我可以按照

Of course, I could serve the file "customers.html" from the dynamic route by following the path explained in Serve Static Files on a Dynamic Route using Express.

但是,我认为这太过分了,这类事情应该可以通过默认的文件扩展名简单地配置,但是我却找不到如何做.有人可以告诉我吗?

However, I think it is an overkill, such sort of things should be simply configurable through the default file extension, but I just could not find how. Can anyone show me?

推荐答案

express static是基于serve-static的,因此您传入设置了extensions属性的options对象.对于您的示例,以下方法将起作用:

express static is based on serve-static so you pass in an options object with the extensions property set. For your example the following would work:

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

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

This sets up express so that if a file is not found eg /customers it will try appending each of the extensions to the path, so in your case /customers.html

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

这篇关于在表达方式中,将默认文件扩展名与静态内容请求相关联的常用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆