【发布时间】:2013-06-03 10:52:18
【问题描述】:
我想提供一个不指定扩展名的 html 文件。有什么方法可以在不定义路线的情况下做到这一点?例如,而不是
/helloworld.html
我只想做
/helloworld
【问题讨论】:
我想提供一个不指定扩展名的 html 文件。有什么方法可以在不定义路线的情况下做到这一点?例如,而不是
/helloworld.html
我只想做
/helloworld
【问题讨论】:
你可以在 express.static 方法中使用扩展选项。
app.use(express.static(path.join(__dirname, 'public'),{index:false,extensions:['html']}));
【讨论】:
app.use(express.static(<public dir>,{extensions:['html']})) 就足够了,否则你必须以example.com/index 的身份访问example.com/index.html。
/ 提供服务,这是非常意外的。
一个快速的'n'dirty解决方案是将.html附加到其中没有句点并且公共目录中存在HTML文件的请求:
var fs = require('fs');
var publicdir = __dirname + '/public';
app.use(function(req, res, next) {
if (req.path.indexOf('.') === -1) {
var file = publicdir + req.path + '.html';
fs.exists(file, function(exists) {
if (exists)
req.url += '.html';
next();
});
}
else
next();
});
app.use(express.static(publicdir));
【讨论】:
.css 扩展名提供 CSS 文件,应该不会有问题(但它会首先检查 .html 文件是否存在,如果它不存在,它将什么也不做,让静态中间件按原样处理)。
这一行可以路由公用文件夹中所有的html文件扩展名。
app.use(express.static('public',{extensions:['html']}));
【讨论】:
虽然罗伯特的回答更优雅,但还有另一种方法可以做到这一点。为了完整起见,我添加了这个答案。要提供不带扩展名的静态文件,您可以创建一个文件夹,其中包含您要提供服务的路由的名称,然后在其中创建一个 index.html 文件。
如果我想在/hello 服务hello.html,以我自己的例子为例。我会创建一个名为hello 的目录并在其中放入一个 index.html 文件。现在,当 '/hello' 被调用时,express 将自动提供该文件而无需扩展名。
有点明显,因为所有 Web 框架都支持这一点,但当时我错过了它。
【讨论】:
如果你想像我一样采用相反的方式(将名为“helloworld”的 html 文件作为 html 提供),这就是我使用的中间件。
var express = require('express');
var app = express();
app.use(function(req, res, next) {
if (req.path.indexOf('.') === -1) {
res.setHeader('Content-Type', 'text/html');
}
next();
});
app.use('/', express.static(__dirname + '/public'));
app.listen(8080, function () {
console.log('App listening on port 8080!');
})
【讨论】: