【golang】解决 gin 的静态文件功能的 JavaScript module script but the server responded with a MIME type of "text/plain" 错误

问题

vite + vue 打包后,扔到 go 的 gin 服务中,windows 莫名报错

go 静态文件代码:

router.Static("/vue_assets", "./vue_static/vue_assets")

错误信息

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". 
Strict MIME type checking is enforced for module scripts per HTML spec.

网上的解决办法

注册表 HKEY_CLASSES_ROOT 有个 .js 项 Content Type=text/plain
改成 Content Type=text/javascript

问题分析

明显是 gin 对于 .js 的静态文件的返回的 Content-Type 依赖于 windows 环境的注册表,那如果换个环境有可能还是会发生错误
需要一个方法来固定下来 .js 返回的 Content-Type

代码调试

通过调试源代码,可知 gin 的静态文件服务依赖于 go http 模块的 静态文件服务
而 http 模块对文件类型的判断则依赖于 mime 模块的文件判断

mime.TypeByExtension(filepath.Ext(name))

如下图:

问题解决

这下就清楚了,通过调查 mime 源码,对 mime 模块设置固定的文件类型来处理就ok

mime.AddExtensionType(".js", "text/javascript; charset=utf-8")

这样 Content-Type 的返回就ok了

posted @ 2022-09-09 11:06  endlesstravel  阅读(2582)  评论(1编辑  收藏  举报