javascript - Python Flask - 错误:“无法加载模块脚本。强制执行严格的 MIME 类型检查”。适用于生产,而不是本地服务器
问题描述
我有这个 html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link
rel="stylesheet"
href="../../../static/css/style.css"
type="text/css" />
<link
rel="stylesheet"
href="../../../static/css/user_header.css"
type="text/css" />
<!--suppress HtmlUnknownTarget -->
<link rel="shortcut icon" href="/favicon.png">
<script type="module" src="../../../static/js/node_connect.js" ></script> <-- Error
<script src="../../../static/lib/jquery.min.js"></script>
<script src="../../../static/lib/selfserve.js"></script>
</head>
有问题的是node_connect.js
文件。在本地启动Flask web工具(Python 3.7.2),打开页面时控制台报如下错误:
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain".
Strict MIME type checking is enforced for module scripts per HTML spec.
检查标题:
Content-Type: text/plain; charset=utf-8
然而,在生产中(当通过 Gunicorn 开始时)它给出了:
Content-Type: application/javascript; charset=utf-8
我猜网络服务器(Apache)在生产案例中为它们提供服务,但另一件事是在测试此网络工具的其他页面时,它们都可以正常工作并正确加载 javascript 文件(即使它们的内容类型是 text/清楚的)。但是,我注意到不同之处在于类型。
这适用于我的情况:
<script src="../../static/js/translator/library/materialize.js"></script>
或这个:
<script type="application/javascript" src="../../static/js/translator/library/materialize.js"></script>
当然,我对有问题的javascript
文件进行了尝试,并收到以下错误(这意味着它现在已加载):
Uncaught SyntaxError: Cannot use import statement outside a module
据我研究,这基本上意味着我需要将类型设置为module
(但这会使浏览器拒绝 .js 文件)。
谁能帮我解决这个问题?
解决方案
问题是由烧瓶如何猜测每个静态文件的内容类型引起的。为此,烧瓶导入mimetypes并调用mimetype, encoding = mimetypes.guess_type(download_name)
该模块从多个来源创建已知 mime 类型的数据库,并使用它返回 mime 类型。
在 Linux 和 MacOS 下mimetypes.py
查看文件:
knownfiles = [
"/etc/mime.types",
"/etc/httpd/mime.types", # Mac OS X
"/etc/httpd/conf/mime.types", # Apache
"/etc/apache/mime.types", # Apache 1
"/etc/apache2/mime.types", # Apache 2
"/usr/local/etc/httpd/conf/mime.types",
"/usr/local/lib/netscape/mime.types",
"/usr/local/etc/httpd/conf/mime.types", # Apache 1.2
"/usr/local/etc/mime.types", # Apache 1.3
]
但在 Windows 下,它会在注册表中查找:
with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr:
for subkeyname in enum_types(hkcr):
try:
with _winreg.OpenKey(hkcr, subkeyname) as subkey:
# Only check file extensions
if not subkeyname.startswith("."):
continue
# raises OSError if no 'Content Type' value
mimetype, datatype = _winreg.QueryValueEx(
subkey, 'Content Type')
if datatype != _winreg.REG_SZ:
continue
self.add_type(mimetype, subkeyname, strict)
因此,要解决烧瓶认为 .js 文件实际上是text/plain
所有必要的问题,只需打开 regedit 并将此注册表项调整为application/javascript
:
推荐阅读
- javascript - 在 Rails 上使用 Javascript 'onbeforeload'
- ebay-api - 如何让 eBay 的 BulkMigrateListing() API 调用工作
- vba - 根据选择的单元格值自动过滤另一个工作表中的表格,其中自动过滤器需要“包含”
- javascript - [[call]] 和 [[construct]] 有什么区别?
- django - 如何在 django2.0.6 的通用删除视图中添加用户身份验证
- jquery - 使用包含,得到太多结果
- c# - 创建模型时无法使用上下文。但是我只有一个 dbcontext?
- azure - 在 Azure App Logics 中获取当前天气
- mysql - mariadb 在小子集上按慢速分组
- sql-server - SQL Server:在所有数据库上运行脚本