Set MIME type for fetched file

736 Views Asked by At

I have a static file server (made with vibe.d) serving a website that uses ES6 modules but with .mjs extension.

My browser (Chromium on Arch Linux) is throwing an error when it fetches the module files server responded with a non-JavaScript MIME type of "application/octet-stream".

It looks like I need to set the MIME type files with the .mjs from "application/octet-stream" to "application/javascript". How do I do this? I could change all the scripts to .js but that is but I would rather figure out how to fix it right.

How would I change the MIME type for a file being fetched? Or probably better, can I change the default MIME type for all .mjs files?

Here is my d code with 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

There are 1 best solutions below

0
On

The content-type header in the response needs to be changed.

Vibe.d might have a way to configure the defaults but you can always catch it before it sends the response to edit the header of files ending in .mjs.

You can do this in vibe.d like so:

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