2

我有一个静态文件服务器(用 vibe.d 制作)为使用 ES6 模块但扩展名为 .mjs 的网站提供服务。

我的浏览器(Arch Linux 上的 Chromium)在获取模块文件时抛出错误server responded with a non-JavaScript MIME type of "application/octet-stream"

看起来我需要使用 .mjs 将 MIME 类型文件从“application/octet-stream”设置为“application/javascript”。我该怎么做呢?我可以将所有脚本更改为.js,但我宁愿弄清楚如何正确修复它。

如何更改正在获取的文件的 MIME 类型?或者可能更好,我可以更改所有 .mjs 文件的默认 MIME 类型吗?

这是我的 vibe.d 代码:

auto router = new URLRouter;
auto fileServerSettings = new HTTPFileServerSettings;
fileServerSettings.encodingFileExtension = ["gzip" : ".gz"];
router.get("/gzip/*", serveStaticFiles("./public/", fileServerSettings));
router.get("/ws", handleWebSockets(&handleWebSocketConnection));
router.get("*", serveStaticFiles("./public/",));

listenHTTP(settings, router);
4

1 回答 1

1

需要更改响应中的内容类型标头。

Vibe.d 可能有一种配置默认值的方法,但您始终可以在它发送响应以编辑以.mjs.

您可以在 vibe.d 中执行此操作,如下所示:

auto router = new URLRouter;
auto fileServerSettings = new HTTPFileServerSettings;
fileServerSettings.encodingFileExtension = ["gzip" : ".gz"];
fileServerSettings.preWriteCallback = &handleMIME; // Add preWriteCallback to fileServerSettings
router.get("/gzip/*", serveStaticFiles("./public/", fileServerSettings));
router.get("/ws", handleWebSockets(&handleWebSocketConnection));
router.get("*", serveStaticFiles("./public/", fileServerSettings)); // Use fileServerSettings in this get too.

// preWriteCallback, will edit the header before vibe.d sends it.
void handleMIME(scope HTTPServerRequest req, scope HTTPServerResponse res, ref string physicalPath) {
    if (physicalPath.endsWith(".mjs")) {
        res.contentType = "application/javascript"; // vibe.d has an easy `.contentType` attribute so you do not have to deal with the header itself.
    }
}
于 2018-09-27T22:42:34.447 回答