JavaScript:导入和脚本类型错误的无限循环

发布于 2025-02-11 23:55:21 字数 1345 浏览 0 评论 0原文

我正在通过localhost:8000运行一个网站,目前我正在无限循环解决此问题。这是用于在我的HTML文件中使用JavaScript文件的行:

    <script type="module" src="./scripts/main.js"></script>

我将类型设置为“模块”在JavaScript文件中使用import。但是我会收到此错误:

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.

当我使用text/javascript作为类型时,我再也无法在JavaScript文件中使用import。因此,我需要使用type =“模块”,现在我在无限循环中。

package.json:

{
    ...
    "main": "main.js",
    "type": "module",
    ...

对于网络服务器,我使用python:

import http.server
import socketserver

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory="PATH_TO_HTML_FILE", **kwargs)


handler = Handler
handler.extensions_map.update({
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript"
})
httpd = socketserver.TCPServer(("localhost", 8000), handler)
print(handler.extensions_map[".js"])
httpd.serve_forever()

输出:

text/javascript

因此,您可以看到它应该是正确的。

I'm running a website on localhost:8000 and I'm currently in an infinite loop for fixing this problem. This is the line for using the javascript file in my html file:

    <script type="module" src="./scripts/main.js"></script>

I set the type to "module" to use import in the JavaScript file. But I get this error:

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.

When I use text/javascript as the type, I can't use import in the JavaScript file anymore. So, I need to use type="module" and now I'm in a infinite loop.

package.json:

{
    ...
    "main": "main.js",
    "type": "module",
    ...

For the webserver I use python:

import http.server
import socketserver

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory="PATH_TO_HTML_FILE", **kwargs)


handler = Handler
handler.extensions_map.update({
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript"
})
httpd = socketserver.TCPServer(("localhost", 8000), handler)
print(handler.extensions_map[".js"])
httpd.serve_forever()

Output:

text/javascript

So, you can see it should be correct.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文