在静态文件中将内容类型设置为XHTML



我想要一个静态文件的路由:

// 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.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")自己设置内容类型。

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

最新更新