Flask+Vite部署Azure后JS模块加载失败,MIME类型错误求助
问题排查与解决
核心原因
你的Flask路由配置大概率把所有请求(包括静态资源请求)都返回了index.html,导致浏览器请求JS模块时,服务器返回的是HTML内容,MIME类型不匹配引发错误。
具体排查与修复步骤
修正Flask路由逻辑
检查你的app.py,如果写了通配路由直接返回index.html,会把静态资源请求也拦截,比如这种错误写法:@app.route('/') @app.route('/<path:path>') def index(path=''): return render_template('index.html')正确做法是先判断请求是否指向静态文件,静态资源请求单独处理,非静态路径再返回
index.html:from flask import Flask, render_template, send_from_directory import os app = Flask(__name__, static_folder='static', static_url_path='/static') @app.route('/') def index(): return render_template('index.html') @app.route('/<path:path>') def catch_all(path): # 检查请求的文件是否存在于static目录 static_file = os.path.join(app.static_folder, path) if os.path.exists(static_file) and os.path.isfile(static_file): return send_from_directory(app.static_folder, path) # 非静态文件请求返回index.html,适配React路由 return render_template('index.html')核对Azure部署的文件结构
确认wwwroot目录结构正确:index.html在根目录,static文件夹和app.py同级,且static内包含前端build生成的js、css等资源。如果前端build的输出位置不对,需要调整Vite的build.outDir配置,确保静态资源和index.html输出到正确路径。验证静态资源的响应头
部署后直接访问静态资源URL(比如https://你的应用域名/static/js/main.xxx.js),查看响应头的Content-Type是否为application/javascript。如果还是text/html,说明路由配置没生效,重新检查Flask代码的执行逻辑。确认Vite的静态资源配置
虽然你移除了base参数,还是要确保vite.config.ts里的assetsDir设置为static,让build后的静态资源统一输出到static目录,和Flask的静态文件夹对应:import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], build: { assetsDir: 'static' } })
内容的提问来源于stack exchange,提问作者Sarah
相关产品推荐
相关产品推荐

