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

http://img3.mukewang.com/639fffc80001010206000103.jpg

我使用 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">

该代码确实发送了正确的文件,但标头错误。

http://img4.mukewang.com/639fffd9000189ee06150609.jpg

手掌心
浏览 139回答 1
1回答

智慧大石

所以我不得不编写自己的文件服务器来手动设置标头,例如:contentTypeMap := map[string]string{&nbsp; &nbsp; ".html": "text/html",&nbsp; &nbsp; ".css":&nbsp; "text/css",&nbsp; &nbsp; ".js":&nbsp; &nbsp;"application/javascript",}filepath.Walk("./dist", func(path string, info os.FileInfo, err error) error {&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalf(err.Error())&nbsp; &nbsp; }&nbsp; &nbsp; if info.IsDir() {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; dirPath := filepath.ToSlash(filepath.Dir(path))&nbsp; &nbsp; contentType := contentTypeMap[filepath.Ext(info.Name())]&nbsp; &nbsp; handlePath := "/" + strings.Join(strings.Split(dirPath, "/")[1:], "/")&nbsp; &nbsp; hf := func(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; w.Header().Add("Content-Type", contentType) // <---- key part&nbsp; &nbsp; &nbsp; &nbsp; http.ServeFile(w, r, path)&nbsp; &nbsp; }&nbsp; &nbsp; if handlePath != "/" {&nbsp; &nbsp; &nbsp; &nbsp; handlePath += "/" + info.Name()&nbsp; &nbsp; }&nbsp; &nbsp; mainRouter.HandleFunc(handlePath, hf)&nbsp; &nbsp; return nil})(如果代码不好,请优化,我自己做了解决方案,我尝试了很多东西来满足我的需要)现在,我收到了带有正确标头的正确文件。而且我找不到任何解决方案来处理http.FileServer在 http 包中使用的自定义标头。如果存在,请提供一个简单的解决方案。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go