VueJs构建产物整合Spring Boot时遭遇白标错误页面问题
解决Vue + Spring Boot 3.x整合部署白标错误问题
核心排查点及解决方案
1. 确认Vue构建配置正确性
- 若使用Vue CLI,在
vue.config.js中确保生产环境的publicPath指向根路径:module.exports = { publicPath: process.env.NODE_ENV === 'production' ? '/' : '/' } - 若使用Vite,在
vite.config.js中设置base为根路径:export default defineConfig({ base: '/' }) - 重新构建前端,保证
dist目录下的index.html中资源引用为根路径格式(如/js/app.xxx.js)。
2. 规范静态资源存放位置
将dist文件夹内的全部内容直接放入src/main/resources/static目录(不要嵌套dist文件夹),最终目录结构示例:
src/main/resources/static/ ├── index.html ├── css/ ├── js/ └── assets/
Spring Boot 3.x默认静态资源优先级:META-INF/resources > resources/static > resources/public,推荐用static目录避免优先级冲突。
3. 处理SPA路由Fallback(关键)
如果Vue使用history模式路由,Spring Boot会把前端路由路径识别为后端接口请求,导致404。需配置WebMvc规则,将非API请求转发到index.html:
- 创建WebMvc配置类:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { // 匹配所有非API的GET请求,转发到index.html registry.addViewController("/**") .setViewName("forward:/index.html"); } } - 若后端有API接口(如前缀
/api/),需排除API路径避免被转发:@Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/") .setViewName("forward:/index.html"); // 排除所有/api开头的路径 registry.addViewController("/**") .setViewName("forward:/index.html") .setPatterns("/*", "/!api/**"); }
4. 检查Spring Boot基础配置
- 确认配置文件(
application.properties/application.yml)中端口为8882,且未设置冲突的上下文路径:server.port=8882 # 若设置了上下文路径(如/server),需同步修改Vue的publicPath为"/server/" # server.servlet.context-path=/server
5. 重新打包部署
- 执行
mvn clean package(Maven)或./gradlew clean build(Gradle),确保静态资源被正确打包进产物。 - 运行打包后的Jar/War文件,避免直接用IDE启动(IDE可能未同步静态资源更新)。
验证步骤
- 启动应用后访问
localhost:8882,查看浏览器控制台是否有资源加载404错误。 - 检查Spring Boot日志,确认不再出现“No mapping for GET /”类报错。
内容的提问来源于stack exchange,提问作者Moa
相关产品推荐
相关产品推荐

