Vite+React生产环境出现MIME类型错误,请求排查建议
生产环境页面加载报错排查方案
问题描述
生产环境启动网页时,浏览器抛出错误:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
项目基于React.js开发,Node.js提供服务,访问URL为https://qaentry.domain.com/It。
相关配置信息
1. package.json scripts配置
"scripts": { "dev": "vite --base=/pmo", "build": "tsc && vite build --base=/pmo", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite --base=/pmo preview" },
2. APP.tsx路由配置
const router = createBrowserRouter([ { path: "/pmo", element: <LandingPage />, } ])
3. 客户端目录结构
- client ---dist -----assets ------ index--_a54pe.js -----index.html
4. Node服务端(SERVER.js)配置
app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "../../client/dist/index.html")); });
5. Vite配置文件
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], build:{ outDir: "dist" } })
排查解决提示
- 静态资源路由优先级问题:当前Node服务的
*路由会拦截所有请求,包括静态资源(比如/pmo/assets/index--_a54pe.js),导致服务器返回index.html而非JS文件,触发MIME类型错误。需先配置静态资源托管,再处理SPA路由:// 先托管dist目录下的静态资源,匹配base路径 app.use('/pmo', express.static(path.join(__dirname, '../../client/dist'))); // 仅在非静态资源请求时返回index.html app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "../../client/dist/index.html")); }); - Base路径与访问URL不匹配:项目配置的Vite base是
/pmo,但实际访问URL为/It,导致静态资源请求路径错误(比如浏览器请求/It/assets/xxx.js,但资源实际在/pmo/assets/xxx.js)。需确认部署路径:- 如果生产环境部署在
/It路径下,修改Vite的base配置为/It,同步更新路由的path为/It,重新构建部署。 - 如果
/It是反向代理到服务的/pmo路径,检查代理规则是否正确,确保静态资源请求被转发到/pmo路径。
- 如果生产环境部署在
- 构建产物路径验证:检查生产环境
dist/index.html中JS资源的引用路径,确认是/pmo/assets/index--_a54pe.js这类正确的绝对路径,避免相对路径或错误路径导致请求错误。 - MIME类型检查:确保Node服务正确设置JS文件的MIME类型,使用
express.static默认会处理,但如果自定义了响应头,需确认未覆盖application/javascript类型。
内容的提问来源于stack exchange,提问作者user2570135
相关产品推荐
相关产品推荐

