登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-13 18:42:38 357浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《提供 CSS 时在 Golang 中出现 MIME 类型('text/plain')错误》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

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


解决方案


我使用的是 Windows 计算机(Windows 10 和 Windows Server 2019),并且我在 javascript 文件上遇到了同样的问题, 我进入注册表 \HKEY_CLASSES_ROOT\.js zq​​bgtzqb“Content Type” 并将其从“text/plain”更改为“application/javascript”,然后重新启动电脑并修复了它

理论要掌握,实操不能落!以上关于《提供 CSS 时在 Golang 中出现 MIME 类型('text/plain')错误》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>