代码之家  ›  专栏  ›  技术社区  ›  Lupus Ossorum

为获取的文件设置MIME类型

  •  1
  • Lupus Ossorum  · 技术社区  · 6 年前

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

    看起来我需要将.mjs的MIME类型文件从“application/octet stream”设置为“application/javascript”。我该怎么做? .js 但那是但我宁愿想办法把它修好。

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

    这是我的d代码和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);
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Lupus Ossorum    6 年前

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

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

    你可以在氛围中这样做。我想:

    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.
        }
    }