为了账号安全,请及时绑定邮箱和手机立即绑定

服务 CSS 时在 Golang 中出现 MIME 类型('text/plain')错误

服务 CSS 时在 Golang 中出现 MIME 类型('text/plain')错误

Go
料青山看我应如是 2023-06-12 09:34:11
我正在构建我的第一个 Go web 项目,当我加载我的页面时,我在浏览器控制台上收到此错误Refused to apply style from 'http://localhost:8080/static/css/processor-auth.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.我不确定我做错了什么,因为我已经添加了这段代码来加载静态文件http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("static"))))这是我的 main.go 文件的样子: package mainimport(    "net/http"    "os"    "html/template"    "github.com/julienschmidt/httprouter")// Auth struct handlertype auth struct{}func (auth *auth) ServeHTTP(w http.ResponseWriter, r *http.Request){    wd,_:= os.Getwd()    t := template.Must(template.ParseFiles(wd+"/templates/processor/auth.html"))    err:=t.Execute(w,nil)    if err !=nil{        http.Error(w,"Could not execute template",500)    }}func main(){    router:= httprouter.New()    // set the static files    http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("static"))))    router.Handler("GET","/auth",&auth{})    server := http.Server{        Addr:"127.0.0.1:8080",        Handler:router,    }    server.ListenAndServe()}编辑:解决了问题因为我用作httprouter多路复用器,所以我无法使用http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("static"))))我必须更新到 httprouter 的 ServeFiles 函数并将代码更新为 router.ServeFiles("/static/*filepath",http.Dir("static"))
查看完整描述

3 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

我使用的是 windows 机器(windows 10 和 windows server 2019),我在 javascript 文件上遇到了同样的问题,我进入注册表并将其从“text/plain”\HKEY_CLASSES_ROOT\.js > "Content Type"更改为“application/javascript”,然后重新启动 PC并修复了它



查看完整回答
反对 回复 2023-06-12
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

为什么会这样?

出现此错误是因为 Go 正在自动检测文件的内容类型。为了进行自动检测,它使用一个映射,该映射指向文件扩展名(如 .js)-> MIME 类型(如文本/纯文本)。要获取此地图,它会从本地机器读取它。因此,如果您的本地计算机在其注册表(或您的操作系统的等效项)中对于 .css 文件的值不正确,并且您使用的代码会自动检测正在提供的文件的 MIME 类型,那么这可能会发生。

什么是注册表设置不正确?

我在重新安装或卸载 Visual Studio 时遇到不正确的注册表值。

Windows修复

您需要使用 regedit 编辑注册表项,以便“内容类型”注册表项指向正确的值。您可以在两个地方找到扩展密钥:

HKEY_CLASSES_ROOT 包含一个列表。就我而言,我在该列表中查找 .js 并将其值从 text/plain 更改为 application/javascript。在原始发帖者的位置,错误似乎在 .css 中,因此您将 HKEY_CLASSES_ROOT\.css 键“内容类型”设置为文本/css。

HKEY_LOCAL_MACHINE\SOFTWARE\CLASSES 也包含一个列表。您应该以相同的方式更新它,使其与 HKEY_CLASSES_ROOT 相匹配。在我的例子中,这已经正确设置为 application/javascript 所以我假设它不是 Go 正在读取的第一个注册表值。


查看完整回答
反对 回复 2023-06-12
?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

我在 Windows 上遇到了这个问题,我通过


func FixMimeTypes() {

    err1 := mime.AddExtensionType(".js", "text/javascript")

    if err1 != nil {

        log.Printf("Error in mime js %s", err1.Error())

    }


    err2 := mime.AddExtensionType(".css", "text/css")

    if err2 != nil {

        log.Printf("Error in mime js %s", err2.Error())

    }

}

查看完整回答
反对 回复 2023-06-12
  • 3 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信