React Webpack构建与Spring Boot后端集成时的服务端渲染问题
问题分析
你的问题出在Spring Boot的路由配置上:当前的RouterFunction会匹配所有GET /*请求,包括前端静态资源(比如bundle.js),导致这些静态资源被以text/html的MIME类型返回,浏览器检测到脚本文件的MIME类型不符合要求,就会拒绝执行。
解决方案
1. 调整Spring Boot路由优先级,优先处理静态资源
修改路由配置,让静态资源请求先被Spring Boot默认的静态资源处理器处理,仅当请求是SPA路由(非静态资源)时才返回index.html。
方案一:使用WebMvcConfigurer配置SPA fallback(推荐)
替换原来的RouterFunction配置为以下代码:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { // 设置最低优先级,仅当其他路由(包括静态资源)都不匹配时才触发 registry.addViewController("/**") .setViewName("forward:/index.html") .setOrder(Ordered.LOWEST_PRECEDENCE); } }
方案二:修改RouterFunction添加路径排除条件
如果你坚持使用RouterFunction,可以添加静态资源路径排除规则:
@Bean public RouterFunction<ServerResponse> htmlRouter(@Value("classpath:/static/index.html") Resource html) { return RouterFunctions.route( GET("/**").and(request -> { String path = request.path(); // 排除静态资源路径和常见静态文件后缀 return !path.startsWith("/static/") && !path.endsWith(".js") && !path.endsWith(".css") && !path.endsWith(".ico") && !path.endsWith(".png") && !path.endsWith(".jpg"); }), request -> ServerResponse.ok().contentType(MediaType.TEXT_HTML).bodyValue(html) ); }
2. 验证Webpack构建配置与资源路径
确保Webpack构建后的静态资源能被Spring Boot正确识别:
- 保持Webpack的
output.publicPath为'/',这样前端资源会以根路径引用(比如/bundle.js) - 构建完成后,将
build目录下的所有文件(包括index.html、bundle.js等)复制到Spring Boot项目的src/main/resources/static目录下,保证静态资源能被Spring Boot的默认静态资源处理器加载
3. 验证静态资源的MIME类型
启动Spring Boot后,直接访问http://localhost:8765/bundle.js,查看响应头的Content-Type是否为application/javascript。如果正确,说明静态资源处理正常,SPA路由也能正常跳转。
内容的提问来源于stack exchange,提问作者Devanshu Ketle
相关产品推荐
相关产品推荐

