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

Angular5+SpringBoot应用页面刷新出现404错误求助

解决Angular+Spring Boot刷新页面404的问题

嘿,我刚碰到过几乎一模一样的坑,这就来帮你搞定!

首先得搞明白为啥刷新会404:你的Angular是单页应用(SPA),第一次访问http://localhost:8080/app时,Spring Boot把你重定向到/myHome/home——这时候是Angular的前端路由在浏览器里处理跳转,根本没给服务器发新请求。但你一刷新页面,浏览器就会直接向服务器请求http://localhost:8080/myHome/home,可Spring Boot后端根本没配置这个路径的接口,自然就返回404了。

接下来分两步解决:

1. 修正Angular打包配置,确保资源路径一致

看你的package.json里build脚本用了--deploy-url="/app/",但index.html的<base href="/myHome">,这俩路径不匹配会导致静态资源加载出错。把deploy-url改成和base href一致:

"scripts": {
  "ng": "ng",
  "start": "ng serve --proxy-config proxy.conf.json",
  "build": "ng build --dev --deploy-url=\"/myHome/\"",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "protractor"
}

改完重新打包Angular,把dist目录里的文件放到Spring Boot的src/main/resources/static/myHome/目录下(这样静态资源就能通过/myHome/xxx正常访问)。

2. 让Spring Boot转发前端路由请求到index.html

你需要让Spring Boot把所有/myHome/**的请求都转发到Angular的index.html,这样刷新时浏览器请求的路由会交给Angular处理。有两种方式可选:

方式一:写一个简单的Controller

创建ForwardController类:

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

@Controller
public class ForwardController {

    // 匹配所有/myHome下的路由请求,转发到index.html
    @GetMapping(value = "/myHome/**")
    public String forwardToIndex() {
        return "forward:/myHome/index.html";
    }
}

方式二:配置WebMvcConfigurer(更灵活)

写一个配置类处理静态资源和路由转发:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射/myHome/**到static/myHome下的静态资源
        registry.addResourceHandler("/myHome/**")
                .addResourceLocations("classpath:/static/myHome/");
        
        // 处理SPA刷新:所有/myHome下的非资源请求转发到index.html
        registry.addResourceHandler("/myHome/**")
                .addResourceLocations("classpath:/static/myHome/index.html")
                .resourceChain(false);
    }
}

做完这两步,重启Spring Boot服务,再刷新/myHome/home页面就不会出现404啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:54:43