前端调用SpringBoot服务接口跨域问题的解决办法

该文章介绍了一种在SpringBoot项目中解决跨域问题的方法,通过实现WebMvcConfigurer接口并添加CORS过滤器配置,允许所有源访问,配置了允许的原始域、请求方法、头部信息以及暴露的头部信息。

要解决跨域问题,增加如下代码到项目中

@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter(){
// 添加CORS配置信息
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 放行哪些原始域
corsConfiguration.addAllowedOrigin("*");
// 是否发送cookie信息
corsConfiguration.setAllowCredentials(false);
// 放行哪些原始域(请求方式)
corsConfiguration.addAllowedMethod("*");
// 放行哪些原始域(头部信息)
corsConfiguration.addAllowedHeader("*");
// 暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
corsConfiguration.addExposedHeader(HttpHeaders.ACCEPT);
// 添加映射路径
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",corsConfiguration);

// 返回新的CorsFileter
return new CorsFilter(source);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
//重写父类提供的跨域请求处理的接口
public void addCorsMappings(CorsRegistry registry) {
//添加映射路径
registry.addMapping("/**")
//放行哪些原始域
.allowedOrigins("*")
//是否发送Cookie信息
.allowCredentials(true)
//放行哪些原始域(请求方式)
.allowedMethods("GET","POST", "PUT", "DELETE")
//放行哪些原始域(头部信息)
.allowedHeaders("*")
//暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
.exposedHeaders("Header1", "Header2");
}
};
}
}

<think>我们正在讨论SpringBoot中解决问题的方法。根据引用内容,有几种常见的方法:1.使用@CrossOrigin注解(局部)2.使用WebMvcConfigurer配置全局CORS(全局)3.使用过滤器(Filter)设置响应头(局部)4.使用ResponseBodyAdvice(全局?引用5提到这种方式,但示例中并未详细说明)5.结合SpringSecurity配置(当项目使用SpringSecurity时)注意:引用1和引用5提到了5种方案,但其中有些是局部配置,有些是全局配置。下面我将详细说明几种主要方法:###1.使用@CrossOrigin注解(局部)这是最直接的方法,可以在控制器类或方法上添加注解,指定允许的源、方法、头信息等。示例代码:```java@RestController@RequestMapping("/api")publicclassMyController{@CrossOrigin(origins="http://localhost:8080")@GetMapping("/hello")publicStringhello(){return"Hello,world!";}}```###2.使用WebMvcConfigurer配置全局CORS(推荐,全局)通过实现`WebMvcConfigurer`接口并重写`addCorsMappings`方法,可以配置全局的CORS规则。示例代码:```java@ConfigurationpublicclassCorsConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddCorsMappings(CorsRegistryregistry){registry.addMapping("/**")//所有接口.allowedOrigins("http://localhost:8080")//允许的源,也可以使用allowedOriginPatterns.allowedMethods("GET","POST","PUT","DELETE")//允许的方法.allowedHeaders("*")//允许的请求头.allowCredentials(true)//允许发送Cookie.maxAge(3600);//预检请求的有效期,单位秒}}```注意:在生产环境中,应使用具体的名替换`http://localhost:8080`,并且当设置`allowCredentials(true)`时,不能使用`allowedOrigins("*")`,而应该使用`allowedOriginPatterns("*")`或指定具体名(引用5)。###3.使用过滤器(Filter)设置响应头(局部)在过滤器中设置响应头,这种方式比较底层,可以灵活控制,但需要手动添加。示例代码:```java@WebFilter("/*")publicclassCorsFilterimplementsFilter{@OverridepublicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,ServletException{HttpServletResponseres=(HttpServletResponse)response;res.setHeader("Access-Control-Allow-Origin","http://localhost:8080");res.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE");res.setHeader("Access-Control-Allow-Headers","*");res.setHeader("Access-Control-Allow-Credentials","true");res.setHeader("Access-Control-Max-Age","3600");chain.doFilter(request,response);}}```然后在启动类上添加`@ServletComponentScan`注解以扫描过滤器。###4.使用ResponseBodyAdvice(引用1提到的方案5)这种方式并不常见,它可以通过全局响应处理来设置头。但通常不推荐,因为其他方式更直接。###5.结合SpringSecurity配置如果项目使用了SpringSecurity,需要在安全配置中启用CORS。示例代码:```java@Configuration@EnableWebSecuritypublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@Overrideprotectedvoidconfigure(HttpSecurityhttp)throwsException{http.cors().and()//启用CORS并调用配置//其他安全配置....csrf().disable();//通常会禁用CSRF}//配置CORS源@BeanCorsConfigurationSourcecorsConfigurationSource(){CorsConfigurationconfiguration=newCorsConfiguration();configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080"));configuration.setAllowedMethods(Arrays.asList("GET","POST"));configuration.setAllowCredentials(true);UrlBasedCorsConfigurationSourcesource=newUrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**",configuration);returnsource;}}```###总结-对于简单的项目,使用`@CrossOrigin`注解即可。-对于前后端分离的项目,推荐使用全局配置(`WebMvcConfigurer`)。-如果使用了SpringSecurity,则需要在安全配置中启用CORS。-过滤器方式适用于需要更细粒度控制的情况。注意事项:-生产环境应指定具体的名,避免使用通配符`*`(尤其是当允许凭证时)。-当设置`allowCredentials(true)`时,`allowedOrigins`不能为`*`,可以使用`allowedOriginPatterns("*")`(SpringBoot2.4.0及以上版本)或指定具体名。以上方法可以帮助你在SpringBoot项目中解决问题[^1][^2][^3][^4][^5]。§§相关问题§§1.在SpringBoot中,使用@CrossOrigin注解和全局配置(WebMvcConfigurer)有什么区别?2.为什么在设置allowCredentials(true)时,allowedOrigins不能使用通配符(*)?3.如果前端SpringBoot后端部署在同一个名下,是否还会存在问题?4.在SpringSecurity中配置CORS时需要注意什么?</think>在 Spring Boot 中解决问题(CORS)主要有以下几种方法,根据使用场景可分为全局配置和局部配置: ### 一、全局配置方案(推荐) #### 1. 实现 `WebMvcConfigurer` 接口(主流方案) ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 所有接口 .allowedOriginPatterns("*") // 允许所有源(生产环境替换为具体名) .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许方法 .allowedHeaders("*") // 允许所有请求头 .allowCredentials(true) // 允许发送Cookie .maxAge(3600); // 预检请求缓存时间(秒) } } ``` **特点**: - 统一管理所有接口规则 - 支持细粒度配置(来源/方法/头信息等) - 适用于前后端分离项目[^1][^5] #### 2. 结合 Spring Security 配置 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() // 启用CORS .csrf().disable() ... // 其他安全配置 } @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOriginPatterns(List.of("https://*.example.com")); config.setAllowedMethods(List.of("*")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } } ``` **注意**:使用 Spring Security 时必须显式启用 CORS[^5] --- ### 二、局部配置方案 #### 1. 使用 `@CrossOrigin` 注解 ```java @RestController public class UserController { // 方法级配置 @CrossOrigin(origins = "http://localhost:3000") @GetMapping("/users") public List<User> getUsers() { ... } // 类级配置(应用到所有方法) @CrossOrigin(maxAge = 1800, allowedHeaders = "*") @RequestMapping("/api/v2") public class ApiV2Controller { ... } } ``` **特点**: - 精确控制单个控制器/方法的规则 - 支持属性:`origins`, `methods`, `allowedHeaders` 等[^3][^4] #### 2. 手动设置响应头(原始方式) ```java @RestController public class ProductController { @GetMapping("/products") public ResponseEntity<?> getProducts(HttpServletResponse response) { // 手动设置响应头 response.setHeader("Access-Control-Allow-Origin", "https://shop.example.com"); return ResponseEntity.ok(productList); } } ``` **适用场景**:早期 Spring Boot 版本或特殊需求[^1] --- ### 三、关键注意事项 1. **生产环境配置**: - 避免使用 `allowedOrigins("*")`,应指定具体名 - 启用凭证时需配置:`allowCredentials(true)` - 凭证模式下通配符需改用:`allowedOriginPatterns("*")`[^5] 2. **预检请求(OPTIONS)**: - 复杂请求会先发送 OPTIONS 预检 - 确保服务器正确处理 `OPTIONS` 方法 3. **常见错误解决**: ```log // 错误示例 Access to XMLHttpRequest at 'http://api.com' from origin 'http://client.com' has been blocked by CORS policy ``` **解决方案**:检查是否遗漏 `@CrossOrigin` 注解或全局配置未生效 --- ### 方案选择建议 | 方案 | 适用场景 | 优势 | |---------------------|----------------------------------|-------------------------| | `WebMvcConfigurer` | 前后端分离项目(主流选择) | 统一管理,减少重复配置 | | `@CrossOrigin` | 特定接口需特殊规则 | 精准控制 | | Spring Security 集成| 已使用安全框架的项目 | 与权限体系无缝结合 | > 推荐优先使用全局配置(`WebMvcConfigurer`),95% 的问题可通过此方案解决[^2][^5]。 [^1]: Spring Boot 解决问题的 5种方案 [^2]: Spring Boot解决问题的方法 [^3]: Spring Boot 中如何解决问题 [^4]: Spring Boot解决问题的方法和示例代码 [^5]: Spring Boot项目问题解决方案详解-五种方案
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值