Flutter Web通过Golang Chi路由部署时MIME类型错误求助
问题:Flutter Web部署到Golang Chi路由后MIME类型错误
用Golang编写后端代码,Flutter Web作为前端,通过Chi路由部署后功能看似正常,但浏览器控制台出现以下错误:
来自“http://localhost:8282/flutter.js”的脚本已加载,但其MIME类型(“text/plain”)不是有效的JavaScript MIME类型。localhost:8282
Uncaught (in promise) DOMException: 操作不安全。无法从Service Worker加载应用,回退到普通标签。flutter.js:145:23
来自“http://localhost:8282/main.dart.js”的脚本已加载,但其MIME类型(“text/plain”)不是有效的JavaScript MIME类型。localhost:8282
现有代码
Golang服务器代码
package main import ( "github.com/go-chi/chi/v5" "log" "net/http" "os" ) func main() { port := os.Getenv("PORT") if port == "" { port = "8282" } router := chi.NewRouter() //Status router for testing if server is working router.Get("/status", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("It is working!!!!!!!!!!!!!!!!!")) }) //Configuring frontend fs := http.FileServer(http.Dir("web")) router.Handle("/*", http.StripPrefix("/", fs)) log.Printf("connect to http://localhost:%s/ for viewing flutter web", port) log.Fatal(http.ListenAndServe("127.0.0.1:"+port, router)) }
Flutter Web的index.html代码
<!DOCTYPE html> <html> <head> <!-- If you are serving your web app in a path other than the root, change the href value below to reflect the base path you are serving from. The path provided below has to start and end with a slash "/" in order for it to work correctly. For more details: * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base This is a placeholder for base href that will be replaced by the value of the `--base-href` argument provided to `flutter build`. --> <base href="/"> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <meta name="description" content="A new Flutter project."> <!-- iOS meta tags & icons --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="futa_web"> <link rel="apple-touch-icon" href="icons/Icon-192.png"> <!-- Favicon --> <link rel="icon" type="image/png" href="favicon.png"/> <title>futa_web</title> <link rel="manifest" href="manifest.json"> <script> // The value below is injected by flutter build, do not touch. var serviceWorkerVersion = '532060023'; </script> <!-- This script adds the flutter initialization JS code --> <script src="flutter.js" defer></script> </head> <body> <script> window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, } }).then(function(engineInitializer) { return engineInitializer.initializeEngine(); }).then(function(appRunner) { return appRunner.runApp(); }); }); </script> </body> </html>
解决方案
问题根源是Golang默认的http.FileServer无法正确识别部分文件的MIME类型,导致.js文件被标记为text/plain,触发浏览器安全限制。需要自定义文件处理器,根据文件扩展名设置正确的Content-Type头:
修改后的Golang代码:
package main import ( "github.com/go-chi/chi/v5" "log" "net/http" "os" "path/filepath" "mime" ) // 自定义文件处理函数,修复MIME类型问题 func customFileServer(fs http.FileSystem) http.Handler { fileServer := http.FileServer(fs) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ext := filepath.Ext(r.URL.Path) if ext != "" { mimeType := mime.TypeByExtension(ext) if mimeType != "" { w.Header().Set("Content-Type", mimeType) } } fileServer.ServeHTTP(w, r) }) } func main() { port := os.Getenv("PORT") if port == "" { port = "8282" } router := chi.NewRouter() router.Get("/status", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("It is working!!!!!!!!!!!!!!!!!")) }) // 使用自定义文件服务器替代默认实现 fs := http.Dir("web") router.Handle("/*", http.StripPrefix("/", customFileServer(fs))) log.Printf("connect to http://localhost:%s/ for viewing flutter web", port) log.Fatal(http.ListenAndServe("127.0.0.1:"+port, router)) }
说明
- 自定义
customFileServer函数会根据请求文件的扩展名,通过mime.TypeByExtension获取正确的MIME类型并设置到响应头中,比如.js文件会被设置为application/javascript - 确保
web目录是flutter build web生成的产物目录,路径配置正确
内容的提问来源于stack exchange,提问作者Kateile
相关产品推荐
相关产品推荐

