I would like to serve an html file without specifying it's extension. Is there any way I can do this without defining a route? For instance instead of
/helloworld.html
I would like to do just
/helloworld
你可以在 express.static 方法中使用扩展选项。
app.use(express.static(path.join(__dirname, 'public'),{index:false,extensions:['html']}));
A quick'n'dirty solution is to attach .html
to requests that don't have a period in them and for which an HTML-file exists in the public directory:
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));
While Robert's answer is more elegant there is another way to do this. I am adding this answer just for the sake of completeness. To serve static files without extension you can create a folder with the name of the route you want to serve against and then create an index.html
file in it.
Taking my own example if I wanted to serve hello.html
at /hello
. I would create a directory called hello
and put an index.html file in it. Now when '/hello' is called express will automatically serve this file without the extension.
Kind of obvious as this is supported by all web frameworks but I missed it back then.
If you want to go the reverse way like I did(serving an html file called "helloworld" as html) this is the middleware I used.
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!');
})
这一行可以路由公共文件夹中的所有 html 文件扩展名。
app.use(express.static('public',{extensions:['html']}));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.