Refused to execute script from ‘xxx’ because its MIME type (‘text/plain’) is not executable.
Toby
Toby

Go 在 Windows 10 上使用 File Server 傳送 JavaScript 的時候間中會出現這個錯誤,網上的其中一個解決方法是更改系統 register 讓 Windows 把 JavaScript 辨認為 text/javascript。然而如果你不想透過更改系統設定的方法解決的話你也可以透過編程方法解決。

使用 Router 來手動設定正確的 Mime Type

func mrouter(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if filepath.Ext(r.RequestURI) == ".js" {
			//Requesting a js file
			w.Header().Add("Content-Type", "text/javascript")
			h.ServeHTTP(w, r)
		} else {
			h.ServeHTTP(w, r)
		}
	})
}

使用方法如下

fs := http.FileServer(http.Dir("./web"))
http.Handle("/", mrouter(fs))

這樣便修好了