已阻止加载“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。重新打开浏览器,成功加载

相关推荐
shimly12345634 分钟前
tcpdump 用法示例
网络·测试工具·tcpdump
xmweisi2 小时前
【华为】报文统计的技术NetStream
运维·服务器·网络·华为认证
VVVVWeiYee2 小时前
BGP配置华为——路径优选验证
运维·网络·华为·信息与通信
yourkin6663 小时前
TCP...
服务器·网络·tcp/ip
哑巴语天雨4 小时前
前端面试-网络协议篇
websocket·网络协议·http·面试·https
ktkiko116 小时前
Websocket——心跳检测
网络·websocket·网络协议
GGGGGGGGGGGGGG.6 小时前
hapxory-ACL基础介绍及案例
运维·服务器·网络
小梁不秃捏7 小时前
HTTP 常见状态码技术解析(应用层)
网络·网络协议·计算机网络·http
网安加云课堂7 小时前
课程分享 | 安全系统建设的挑战与解决方案
网络·安全·web安全
learning-striving8 小时前
eNSP下载安装(eNsp、WinPcap、Wireshark、VirtualBox下载安装)
网络·计算机网络·华为·路由器·ensp·交换机