有什么方法可以在没有扩展名的情况下从 express 提供静态 html 文件? [英] Any way to serve static html files from express without the extension?

查看:28
本文介绍了有什么方法可以在没有扩展名的情况下从 express 提供静态 html 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提供一个 html 文件而不指定它的扩展名.有没有什么办法可以在不定义路线的情况下做到这一点?例如,而不是

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

我只想做

 /helloworld

推荐答案

一个快速的解决方案是将 .html 附加到没有句点的请求中公共目录中存在 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));

这篇关于有什么方法可以在没有扩展名的情况下从 express 提供静态 html 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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