[英]Failed to load module script: Expected a JavaScript module [vite] [react] [golang]
I am using vite as build tool for my react app and golang as backend.我使用 vite 作为我的 react 应用程序的构建工具,使用 golang 作为后端。
I built the app for production and host the app on my http server.我构建了用于生产的应用程序并将该应用程序托管在我的 http 服务器上。
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)要托管我的文件,代码看起来像(在 main.go 中)
fs := http.FileServer(http.Dir("./dist"))
http.Handle("/", fs)
in index.html在 index.html 中
<script type="module" crossorigin src="/assets/index.fd457ca0.js"></script>
<link rel="stylesheet" href="/assets/index.bdcfd918.css">
The code did actually send correct files but with wrong headers.该代码确实发送了正确的文件,但标题错误。
So I had to write my own file server to set the headers manually like:所以我不得不编写自己的文件服务器来手动设置标题,例如:
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
})
(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.而且我找不到任何解决方案来使用 http 包中的
http.FileServer
处理自定义标头。 And please provide a easy solution if it exists.如果存在,请提供一个简单的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.