任何方式提供静态html文件从快递没有扩展名? [英] Any way to serve static html files from express without the extension?

查看:112
本文介绍了任何方式提供静态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));

这篇关于任何方式提供静态html文件从快递没有扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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