【问题标题】:Getting MIME type ('text/plain') error in Golang while serving CSS在提供 CSS 时在 Golang 中出现 MIME 类型('text/plain')错误
【发布时间】:2020-12-05 04:44:55
【问题描述】:

我正在构建我的第一个 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 main

import(
    "net/http"
    "os"
    "html/template"

    "github.com/julienschmidt/httprouter"
)


// Auth struct handler
type 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"))

【问题讨论】:

    标签: go


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      为什么会这样?

      出现此错误是因为 Go 会自动检测文件的内容类型。为了进行自动检测,它使用从文件扩展名(如 .js)-> MIME 类型(如 text/plain)指向的映射。为了得到这张地图,它从本地机器上读取它。因此,如果您的本地计算机在其注册表(或您的操作系统的等效项)中为 .css 文件提供了不正确的值,并且您使用的代码会自动检测所服务文件的 MIME 类型,则可能会发生这种情况。

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

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

      Windows 修复

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

      HKEY_CLASSES_ROOT 包含一个列表。就我而言,我在该列表中查找 .js 并将其值从 text/plain 更改为 application/javascript。在原始海报的位置,错误似乎在 .css 中,因此您将 HKEY_CLASSES_ROOT\.css 键“Content Type”设置为 text/css。

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

      参考

      去问题:https://github.com/golang/go/issues/32350

      【讨论】:

        猜你喜欢
        • 2012-06-02
        • 2021-08-27
        • 2021-08-27
        • 2020-11-20
        • 2012-03-23
        • 2018-12-13
        • 2018-03-19
        • 2013-12-24
        相关资源
        最近更新 更多