简体   繁体   中英

Set MIME type for fetched file

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM