React与Spring Boot集成问题:Webpack构建后MIME类型错误
问题原因
你的Spring Boot路由把所有GET请求(/*)都返回index.html,连静态资源(比如bundle.js)的请求也不放过。浏览器请求bundle.js时,服务器返回的是HTML文件(MIME类型text/html),但浏览器要的是JS文件(application/javascript),所以触发了严格MIME类型检查的错误。
解决步骤
1. 让Spring Boot正确加载静态资源
把Webpack构建的前端文件(bundle.js、CSS、图片等)放到Spring Boot的src/main/resources/static目录里——Spring Boot默认会从这里加载静态资源,直接通过/bundle.js这类路径就能访问。
可以直接修改Webpack的输出路径,省去手动复制的麻烦:
output: { path: path.join(__dirname, '../src/main/resources/static'), // 按需调整路径,适配你的项目结构 publicPath: '/', filename: 'bundle.js', }
2. 修改路由规则,排除静态资源请求
调整Spring Boot的RouterFunction,只对非静态资源的路由请求返回index.html:
@Bean public RouterFunction<ServerResponse> htmlRouter(@Value("classpath:/static/index.html") Resource html) { return RouterFunctions.route( GET("/**") .and(request -> { String path = request.path().toString(); // 排除常见静态资源后缀,可根据实际需求添加 return !path.matches(".*\\.(js|css|png|jpg|gif|ico|svg|woff2|woff|ttf)$"); }), request -> ServerResponse.ok().contentType(MediaType.TEXT_HTML).bodyValue(html) ); }
3. 验证前端资源引用路径
确保index.html里引用bundle.js的路径正确,比如:
<script src="/bundle.js"></script>
因为Webpack配置了publicPath: '/',所以用根路径引用即可,Spring Boot会从静态目录正确加载资源。
补充提示
如果你的应用部署在上下文路径下(比如/abc),需要将Webpack的publicPath改为/abc/,同时调整Spring Boot的相关配置,保证所有路径匹配一致。
内容的提问来源于stack exchange,提问作者Ashish Choudhary
相关产品推荐
相关产品推荐

