Any way to serve static html files from express without the extension?

前端 未结 4 2086
青春惊慌失措
青春惊慌失措 2020-12-03 07:45

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

 /he         


        
相关标签:
4条回答
  • 2020-12-03 07:57

    you can just use extension option in express.static method .

    app.use(express.static(path.join(__dirname, 'public'),{index:false,extensions:['html']}));
    
    0 讨论(0)
  • 2020-12-03 08:03

    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));
    
    0 讨论(0)
  • 2020-12-03 08:16

    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.

    0 讨论(0)
  • 2020-12-03 08:19

    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!');
    })
    
    0 讨论(0)
提交回复
热议问题