Spring Boot多模块Maven项目中Angular前端与后端如何连通?
问题根因
从你给出的frontend打包产物可以看到,所有Angular构建后的文件都被放在了static/frontend二级目录下,Spring Boot默认会从classpath:/static/、classpath:/public/等目录下直接加载根路径资源,你现在的index.html实际路径是/frontend/index.html,直接访问localhost:8080/当然会返回404。
解决方案
以下三个方案任选其一即可,推荐方案1改动最小适配性最高:
方案1:修改Angular构建输出路径,取消二级目录
Angular默认ng build会把产物放到dist/<项目名>目录下,你这里项目名是frontend,所以多了一层frontend目录。修改angular.json配置:
找到projects -> frontend -> architect -> build -> options下的outputPath配置,把默认值dist/frontend改成dist。
改完之后重新执行mvn clean package,构建后的产物会直接放到static/根目录下,访问localhost:8080/就能直接加载index.html。
方案2:新增Spring MVC映射配置
如果不想修改前端构建配置,可以在backend模块新增Spring MVC配置类,手动指定静态资源查找路径:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 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 addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/frontend/"); } // 适配SPA前端路由,解决刷新404问题 @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/index.html"); // 如果前端使用history路由模式,且后端接口统一用/api前缀,可以加下面的配置,把所有非接口请求转发到index.html registry.addViewController("/**/{path:[^\\.]*}").setViewName("forward:/index.html"); } }
方案3:临时测试方案
无需修改配置,直接访问http://localhost:8080/frontend/即可加载前端页面,但是路径会多一层前缀,不推荐生产环境使用。
额外检查项
如果修改后仍有资源加载异常,可以检查Angular项目index.html中的<base href="/">配置,部署在根路径时保持默认值/即可,部署在子路径时需要修改为对应的前缀。
内容的提问来源于stack exchange,提问作者milanHrabos

