【问题标题】:How do i force express to serve static html documents having no file extentions with 'text/html' content type我如何强制 express 提供没有文件扩展名且内容类型为“text/html”的静态 html 文档
【发布时间】:2020-01-20 04:20:37
【问题描述】:

我用编码为“utf-8”的html文件制作了一个静态生成的网站

从快递服务 它们驻留在静态目录中

我在保存之前省略了网页的文件扩展名后发现

当在浏览器中打开网页时,网页会被下载,而不是像通常那样呈现为 html 文档

到目前为止,找不到任何有关该主题的相关信息。

【问题讨论】:

  • 所以你想使用无扩展名的文件作为html?
  • 准确地说,Aritra Chakraborty
  • 我还没有测试你的解决方案,但我假设扩展选项告诉 express 默认将文件视为 HTML
  • @JOHNSWANA — 没有。如果 URL 是 /static/example 并且没有 example 文件,它会告诉 express 查找 example.html

标签: javascript node.js


【解决方案1】:

静态模块接受setHeaders 函数,该函数可以动态地将标题添加到它所服务的任何静态文件中。

您可以测试文件是否没有文件扩展名并动态添加标题:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

// This is a bit quick and dirty, but should be suitable for most cases
const noFileExtension = /[^.]{5}$/;

const staticOptions = {
    setHeaders: (res, path, stat) => { 
        if (path.match(noFileExtension)) {
            res.set('Content-Type', "text/html");
        }
    }
}
app.use(express.static('public', staticOptions));

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

【讨论】:

    【解决方案2】:

    一个非常hacky的方法是在静态选项中设置标题。现在您可以添加 if 子句来说明路径是否没有扩展名等。但基本上这会起作用:

    const express = require('express');
    const app = express();
    
    app.use(express.static(<your directory>, {
      setHeaders: function (res, path, stat) {
        res.set('Content-Type', 'text/html');
      }
    }))
    
    app.listen(8080);
    

    【讨论】:

      猜你喜欢
      • 2018-10-19
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多