加载模块脚本失败:预期为JavaScript模块。

huangapple go评论80阅读模式
英文:

Failed to load module script: Expected a JavaScript module

问题

我是你的中文翻译助手,以下是你要翻译的内容:

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

代码实际上发送了正确的文件,但是使用了错误的头部。

英文:

加载模块脚本失败:预期为JavaScript模块。

I am using vite as build tool for my react app and golang as backend.

I built the app for production and host the app on my http server.

my directory structure:

server
  |- dist
  |    | index.html
  |    |- assets
  |         | index.js
  |         | index.css
  | main.go

To host my files the code looks like (inside main.go)

fs := http.FileServer(http.Dir(&quot;./dist&quot;))
http.Handle(&quot;/&quot;, fs)

in index.html

&lt;script type=&quot;module&quot; crossorigin src=&quot;/assets/index.fd457ca0.js&quot;&gt;&lt;/script&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;/assets/index.bdcfd918.css&quot;&gt;

The code did actually send correct files but with wrong headers.

加载模块脚本失败:预期为JavaScript模块。

答案1

得分: 0

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

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) // <---- 关键部分
        http.ServeFile(w, r, path)
    }

    if handlePath != "/" {
        handlePath += "/" + info.Name()
    }

    mainRouter.HandleFunc(handlePath, hf)
    return nil
})

(如果代码有问题,请进行优化,我自己制作了这个解决方案,并尝试了很多方法来满足我的需求)

现在,我使用正确的头部接收到了正确的文件。

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

英文:

So I had to write my own file server to set the headers manually like:

contentTypeMap := map[string]string{
	&quot;.html&quot;: &quot;text/html&quot;,
	&quot;.css&quot;:  &quot;text/css&quot;,
	&quot;.js&quot;:   &quot;application/javascript&quot;,
}

filepath.Walk(&quot;./dist&quot;, 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 := &quot;/&quot; + strings.Join(strings.Split(dirPath, &quot;/&quot;)[1:], &quot;/&quot;)

	hf := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add(&quot;Content-Type&quot;, contentType) // &lt;---- key part
		http.ServeFile(w, r, path)
	}

	if handlePath != &quot;/&quot; {
		handlePath += &quot;/&quot; + info.Name()
	}

	mainRouter.HandleFunc(handlePath, hf)
	return nil
})

(please optimize if the code is bad, I made the solution myself and I tried so many stuff to fit my needs)

Now with that I recevied the correct files with correct headers.

And I couldn't find any solutions to work with custom headers using http.FileServer in http package. And please provide a easy solution if it exists.

huangapple
  • 本文由 发表于 2022年5月31日 12:01:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/72442139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定