已阻止加载“http://localhost:8086/xxx.js”的模块,它使用了不允许的 MIME 类型 (“text/plain”)。

记录今天解决的一个小bug

在终端启动8080端口号监听后,打开网址http://localhost:8080,发现不能正确加载页面,打开检查-控制台,出现如下警告:已阻止加载"http://localhost:8086/xxx.js"的模块,它使用了不允许的 MIME 类型 ("text/plain")。

问题的根本原因是静态文件的 MIME 类型错误 。由于使用的是 Python 的 http.server 来提供文件,它默认将 .js 文件的 MIME 类型设为 text/plain,导致浏览器拒绝加载这些文件。

在网上找了一些方法试了没用,借助gpt,发现可以通过手动设置 Python 服务器的 MIME 类型,但是不太推荐。

1.创建如下代码,如a.py

python 复制代码
import http.server
import socketserver
import mimetypes

PORT = 8086
DIRECTORY = "."

class Handler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header("Cache-Control", "no-store")
        super().end_headers()

    def guess_type(self, path):
        # Ensure .js files are served with the correct MIME type
        if path.endswith(".js"):
            return "application/javascript"
        return super().guess_type(path)

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print(f"Serving at port {PORT}")
    httpd.serve_forever()
  1. 进入a.py的目录,并运行这个脚本

python custom_http_server.py

3。重新打开浏览器,成功加载

相关推荐
CodeYp201916 分钟前
第3讲:网络命令
linux·网络·命令
承渊政道18 小时前
Linux网络学习【Reactor反应堆模式】
linux·网络·学习·ubuntu·reactor
爱和冰阔落1 天前
【Linux网络】TCP 服务器如何并发处理多个客户端?从 fork、僵尸进程到双重 fork
linux·运维·服务器·网络
严肃小白兔1 天前
Cloudflare 更新 API Token 管理:从最小权限到自动化凭据安全
网络·安全·自动化
Linux-lucky1 天前
45-Linux学习之旅之防火墙与WEB加固
linux·前端·网络·学习·ubuntu
博客zhu虎康2 天前
实现局域网P2P通信:内网发送消息
网络·网络协议·p2p
吴声子夜歌2 天前
Kubernetes权威指南——网络原理(一)
网络·容器·kubernetes
陈希1232 天前
Linux 服务器性能排查手册(2026):CPU、内存、磁盘IO、网络四大瓶颈定位
linux·服务器·网络
国科安芯2 天前
从遥控到自治:ASP4644S2B支撑星载电源健康管理与容错配电
网络·单片机·嵌入式硬件·安全·dcdc·低轨卫星·商业航天
|_⊙2 天前
网络层协议 IP
服务器·网络·tcp/ip