Node.js 有没有办法从express提供静态html文件而不使用扩展名?

Node.js 有没有办法从express提供静态html文件而不使用扩展名?,node.js,express,Node.js,Express,我想在不指定扩展名的情况下提供html文件。我有没有办法不用定义路线就能做到这一点?例如,而不是 /helloworld.html 我想做的只是 /helloworld 一个快速的“脏”解决方案是将.html附加到没有句点且公共目录中存在html文件的请求: var fs = require('fs'); var publicdir = __dirname + '/public'; app.use(function(req, res, next) { if (req.

我想在不指定扩展名的情况下提供html文件。我有没有办法不用定义路线就能做到这一点?例如,而不是

 /helloworld.html
我想做的只是

 /helloworld

一个快速的“脏”解决方案是将
.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));

虽然罗伯特的回答更为优雅,但还有另一种方法可以做到这一点。我添加这个答案只是为了完整性。要提供不带扩展名的静态文件,您可以创建一个包含要提供服务的路由名称的文件夹,然后在其中创建一个
index.html
文件

举我自己的例子,如果我想在
/hello
上提供
hello.html
。我将创建一个名为
hello
的目录,并在其中放置一个index.html文件。现在,当调用“/hello”时,express将自动提供此文件,而不带扩展名


这一点很明显,因为所有web框架都支持这一点,但我当时错过了

您可以在express.static方法中使用扩展选项

app.use(express.static(path.join(__dirname, 'public'),{index:false,extensions:['html']}));

如果您想像我一样走相反的路(将一个名为“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!');
})

这一行可以路由公用文件夹中的所有html文件扩展名

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

很好,只有一个问题。这会拦截所有的公共请求吗?假设我想在公共目录中为CSS服务,我将添加扩展,那么这会中断吗?它只考虑在文件名中没有句点的请求。因此,如果您使用
.CSS
扩展名为CSS文件提供服务,应该不会有问题(但它会首先检查
.html
文件的存在,如果它不存在,它将什么也不做,让静态中间件照原样处理)。很好的回答dai
应用程序。使用(express.static(,{extensions:['html'])
就足够了,否则,您必须以
example.com/index.html
的身份访问
example.com/index
。这应该是最重要的答案。在推出live之后,我们亲身体验到,一个无法从
/
中提供的index.html是非常意外的。在更大的项目中并不真正可行