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

无法加载模块脚本:需要一个 JavaScript 模块

无法加载模块脚本:需要一个 JavaScript 模块

Go
手掌心 2022-12-19 14:07:26
我使用 vite 作为我的 React 应用程序的构建工具,并使用 golang 作为后端。我构建了用于生产的应用程序并将该应用程序托管在我的 http 服务器上。我的目录结构:server  |- dist  |    | index.html  |    |- assets  |         | index.js  |         | index.css  | main.go托管我的文件的代码看起来像(在 main.go 中)fs := http.FileServer(http.Dir("./dist"))http.Handle("/", fs)在 index.html 中<script type="module" crossorigin src="/assets/index.fd457ca0.js"></script><link rel="stylesheet" href="/assets/index.bdcfd918.css">该代码确实发送了正确的文件,但标头错误。
查看完整描述

1 回答

?
智慧大石

TA贡献1946条经验 获得超3个赞

所以我不得不编写自己的文件服务器来手动设置标头,例如:


contentTypeMap := map[string]string{

    ".html": "text/html",

    ".css":  "text/css",

    ".js":   "application/javascript",

}


filepath.Walk("./dist", func(path string, info os.FileInfo, err error) error {

    if err != nil {

        log.Fatalf(err.Error())

    }

    if info.IsDir() {

        return err

    }


    dirPath := filepath.ToSlash(filepath.Dir(path))

    contentType := contentTypeMap[filepath.Ext(info.Name())]

    handlePath := "/" + strings.Join(strings.Split(dirPath, "/")[1:], "/")


    hf := func(w http.ResponseWriter, r *http.Request) {

        w.Header().Add("Content-Type", contentType) // <---- key part

        http.ServeFile(w, r, path)

    }


    if handlePath != "/" {

        handlePath += "/" + info.Name()

    }


    mainRouter.HandleFunc(handlePath, hf)

    return nil

})

(如果代码不好,请优化,我自己做了解决方案,我尝试了很多东西来满足我的需要)


现在,我收到了带有正确标头的正确文件。


而且我找不到任何解决方案来处理http.FileServer在 http 包中使用的自定义标头。如果存在,请提供一个简单的解决方案。


查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 138 浏览
慕课专栏
更多

添加回答

举报

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