You need to enable JavaScript to run this app. 如何在Spring Boot服务器中托管Angular项目的编译构建文件
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot服务器中托管Angular项目的编译构建文件

问题解决步骤

1. 修正访问路径

你配置了server.servlet.context-path: /api/,意味着所有服务路径都统一加了/api前缀,直接访问http://localhost:8002/本身就不会被服务识别,首先需要调整访问前缀。
同时你的spring.mvc.static-path-pattern: "/resources/**"配置指定了静态资源的访问路径必须匹配/resources/**规则,所以静态资源的根访问路径应该是http://localhost:8002/api/resources/。
可选优化:如果不想静态资源访问路径带/resources前缀,可以将spring.mvc.static-path-pattern修改为/**,后续白名单配置同步调整即可。

2. 修正静态资源存放位置

Spring Boot默认扫描的静态资源目录是src/main/resources下的以下4个路径:

  • /META-INF/resources/
  • /resources/
  • /static/
  • /public/
    你现在嵌套了两层resources目录(src/main/resources/resources/static/)属于冗余配置,直接把Angular编译产物放到src/main/resources/static/目录下即可。

3. 放开静态资源的JWT拦截

你当前的JwtFilter只放过了/api/auth相关路径,静态资源的访问请求会被拦截校验登录状态,未登录的情况下会直接返回错误,不会走到静态资源解析逻辑。需要修改shouldNotFilter方法,将静态资源路径加入白名单:

@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
    String path = request.getRequestURI();
    return path.startsWith("/api/auth") || path.startsWith("/api/resources/");
}

如果之前修改了静态资源匹配规则为/**,可以根据实际情况调整白名单规则,比如匹配.html/.js/.css等静态资源后缀,或者直接放过所有根路径下的非接口请求。

4. 可选:适配Angular HTML5路由

如果你的Angular项目用了不带#的HTML5路由模式,还需要加资源映射配置,让所有前端路由都fallback到index.html,否则刷新前端子路由会出现404:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("classpath:/static/")
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) throws IOException {
                        Resource requestedResource = location.createRelative(resourcePath);
                        return requestedResource.exists() && requestedResource.isReadable() ? requestedResource : location.createRelative("index.html");
                    }
                });
    }
}

完成以上配置后,访问对应静态资源路径即可正常加载Angular页面。

内容的提问来源于stack exchange,提问作者Nikhil.Nixel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 07:45:02