【问题标题】:Set content-type to XHTML in static files在静态文件中将 content-type 设置为 XHTML
【发布时间】:2020-03-04 12:39:49
【问题描述】:

我想为我的静态文件设置路由:

// server.js
app.use('/', require('./routes/ui/templates'));

问题是我无法从 html->xhtml 更改内容类型。这是我的路线:

const express = require('express');
const router = express.Router();

// Path configs
const pathRoot = __dirname
const pathPublic = pathRoot + "/../../public/" 

router.use('/', express.static(pathPublic));

router.get('/', (req, res) => {
    console.log(pathPublic)
    res.sendFile('index.html', {root: pathRoot});
})

router.use((req, res, next) => {
    res.type('application/xhtml+xml');
    next();
})

module.exports = router;

请注意,由于某种原因,如果我不添加 router.use(...) 我的索引文件根本没有提供。据我了解,我拥有的中间件 写的应该是最后一个,因为我试图捕获响应并修改它。 如果我错了,请纠正我。

【问题讨论】:

    标签: express


    【解决方案1】:

    如果您想为express.static() 发送的特定类型的文件管理Content-Type,您可以使用setHeaders 选项,如下所示:

    app.use(express.static(path.join(__dirname, "public"), {
        setHeaders: function(res, path, stat) {
            // if file is a .xml file, then set content-type
            if (path.endsWith(".xml")) {
                res.setHeader("Content-Type", "application/xhtml+xml");
            }
        }
    }));
    

    您可能还会询问其他一些问题:

    1. 一旦你的express.static() 路由匹配一个文件,就不会进行进一步的路由。响应已发送,并且不会调用任何后续的路由处理程序。因此,您不能用以后的路由影响其他地方的内容类型。

    2. 如果请求路由路径是/,那么express.static() 将在您传递的pathPublic 中查找index.html 文件。如果它找到它,它将发送它,并且不会发生进一步的路由。

    3. res.type() 并没有做您似乎试图使用它的事情。您将文件扩展名传递给它,它会根据该文件扩展名的 mime 查找设置内容类型。正如您在上面的代码示例中看到的那样,您可以使用res.setHeader("Content-Type", "application/xhtml+xml") 自己设置内容类型。

    【讨论】:

      【解决方案2】:

      试试res.setHeader('content-type', 'application/xhtml+xml');

      【讨论】:

        猜你喜欢
        • 2012-05-22
        • 1970-01-01
        • 1970-01-01
        • 2013-01-20
        • 1970-01-01
        • 2011-10-04
        • 2014-08-22
        • 1970-01-01
        • 2021-04-26
        相关资源
        最近更新 更多