You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue Router+Spring Boot路由失效,点击/访问URL出现白标错误

问题解决:Vue Router + Spring Boot同端口部署后路由失效(Whitelabel Error Page)

核心原因

Vue Router使用createWebHistory()(history模式)时,直接访问路由URL或跳转后,请求会被Spring Boot的DispatcherServlet接管,而Spring Boot没有对应这些路径的控制器,所以返回404错误页面。同时代码里还有几处小问题需要修正。

分步解决方案

1. 修正Vue路由跳转路径

你的App.vue中$router.push的路径缺少开头的/,导致生成相对路径,跳转时出现错误:

<script>
export default {
  methods: {
    goToRegistration() {
      // 修正为绝对路径
      this.$router.push('/omg/registration');
    },
  },
};
</script>

2. 配置Vue Router的基础路径(可选但推荐)

因为前端资源最终部署在Spring Boot的static目录下,建议在创建Router时指定base路径,避免路径冲突:

// router.js
const router = createRouter({
  // 若前端部署后根路径为/,保持默认即可;有前缀则对应调整
  history: createWebHistory('/'),
  routes,
});

3. 关键:配置Spring Boot重定向所有前端路由到index.html

添加控制器或配置全局重定向,让所有匹配前端路由的请求都返回index.html,交由Vue Router接管处理:

方式一:添加控制器

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SpaController {
    // 匹配所有以/omg/开头的前端路由路径
    @GetMapping("/omg/**")
    public String forwardToIndex() {
        return "forward:/index.html";
    }

    // 根路径访问时也重定向到index.html
    @GetMapping("/")
    public String rootForward() {
        return "forward:/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 WebConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/omg/**").setViewName("forward:/index.html");
        registry.addViewController("/").setViewName("forward:/index.html");
    }
}

4. 验证前端构建与部署

确认frontend-maven-plugin正确执行了npm run build,且maven-resources-plugin已将src/frontend/dist下的文件复制到Spring Boot的target/classes/static目录中,检查该目录下是否存在index.html及对应的js、css资源。

额外注意点

  • vue.config.js中的代理配置仅用于开发环境,部署到Spring Boot后无需依赖该代理,API请求可直接使用相对路径。
  • 若启用Spring Security,需确保这些前端路由路径被允许匿名访问,避免被权限拦截。

内容的提问来源于stack exchange,提问作者eleftheria christopoulou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:35:17