Spring Boot应用中带Context-Path的CORS配置问题
问题
Spring Boot应用中配置CORS时遇到问题:
已配置Context-Path如下:
server: port: 8081 servlet: context-path: '/api'
CORS配置代码:
import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc @ConfigurationProperties(prefix = "web.cors") @Getter @Setter public class CorsConfiguration implements WebMvcConfigurer { private String allowedOrigins; private String allowedMethods; @Override public void addCorsMappings(CorsRegistry registry) { registry .addMapping("/api/**") .allowedOrigins(allowedOrigins.split(",")) .allowedMethods("*") .allowedHeaders("*"); } }
application.yaml中的CORS配置:
web: cors: allowed-origins: http://localhost:8080, http://localhost allowed-methods: GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD
前端运行在http://localhost:8080,调用GET /api/markets时出现CORS错误,但将CORS配置中的.addMapping("/api/**")改为.addMapping("/**")即可正常工作。询问是否遗漏了与Context-Path相关的设置。
原因分析
Spring Boot中,CorsRegistry的addMapping方法接收的路径是相对于Context-Path的路径,而非完整的请求路径。
你的应用设置了context-path: '/api',当前端请求/api/markets时,Spring Boot会先剥离Context-Path,实际匹配映射的路径是/markets。此时你配置的/api/**根本无法匹配到这个路径,自然不会应用CORS规则,导致跨域错误;而/**会匹配所有剥离Context-Path后的路径,所以能正常生效。
解决方案
直接将CORS映射路径改为/**即可覆盖所有基于当前Context-Path的请求,这也是最简洁的配置方式:
@Override public void addCorsMappings(CorsRegistry registry) { registry .addMapping("/**") .allowedOrigins(allowedOrigins.split(",")) .allowedMethods("*") .allowedHeaders("*"); }
如果需要更精细的控制(比如只允许特定子路径的跨域),只需针对剥离Context-Path后的路径配置映射即可。例如,若想只允许/api/markets相关的请求,可配置.addMapping("/markets/**")。
内容的提问来源于stack exchange,提问作者Ghassen
相关产品推荐
相关产品推荐

