关于配置cors跨域

普通web项目:

1.首先引入jar包

在lib文件夹中添加jar

1)cors-filter-2.4.jar

2)java-property-utils-1.9.1.jar

2.在web.xml中加入配置

webapp节点下加入如下编码:
        <filter>
		<filter-name>CORS</filter-name>
		<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>CORS</filter-name>
		<servlet-name>/*</servlet-name>
	</filter-mapping>
	<filter-mapping>
		<filter-name>CORS</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

相关网页:http://software.dzhuvinov.com/cors-filter-installation.html

springboot项目:
经过尝试在pom.xml引入依赖,再配置web.xml,这个方法没有跨域成功。
正确方式:在src/package任意地方新建类
package com.monetware.config;
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.servlet.config.annotation.CorsRegistry;  
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;  
    
@Configuration  
public class CorsConfig extends WebMvcConfigurerAdapter {  
  
    @Override  
    public void addCorsMappings(CorsRegistry registry) {  
        registry.addMapping("/**")  
                .allowedOrigins("*")  
                .allowCredentials(true)  
                .allowedMethods("GET", "POST", "DELETE", "PUT")  
                .maxAge(3600);  
    }  
  
}  

这样就解决了跨域问题
<think>嗯,用户想了解如何在Spring Boot后端应用中配置CORS以支持请求。首先,我得回忆一下CORS的基本概念。CORS源资源共享,用于解决浏览器同源策略限制的问题。当前端应用和后端不在同一个时,浏览器会阻止请求,这时候需要后端配置CORS允许特定的来源、方法或头信息。 接下来,我得考虑Spring Boot中常见的配置方法。通常有两种方式:全局配置和基于注解的局部配置。全局配置可能通过一个配置类,使用WebMvcConfigurer或者Filter的方式。而局部配置则是针对特定的控制器或方法使用@CrossOrigin注解。 首先,全局配置。记得Spring Boot可以通过实现WebMvcConfigurer接口,然后重写addCorsMappings方法。需要设置allowedOrigins,allowedMethods等参数。这时候应该创建一个配置类,比如CorsConfig,然后加上@Configuration注解。同时,使用registry.addMapping来指定路径,比如/**表示所有路径。允许的来源可以是具体的名,或者用"*"表示允许所有,但通常不建议用通配符,特别是当需要携带凭证时。 另外,可能还需要设置allowedHeaders,exposedHeaders,allowCredentials等。比如,如果前端需要携带认证信息,allowCredentials应该设为true,此时allowedOrigins不能是通配符,必须明确指定来源。这部分需要注意细节,否则配置可能不生效。 然后是局部配置,使用@CrossOrigin注解。这个注解可以用在控制器类或者方法上,指定origins、methods等属性。这种方式适合对某些特定的接口进行细粒度控制。但如果有多个接口需要配置,全局配置会更方便。 另外,可能还有一种方式是通过Filter配置。创建CorsFilter,并注册到Spring容器中。不过这种方法可能不如前两种常用,但有时候在特定场景下可能需要。 用户的问题可能还涉及到实际配置中的常见问题,比如为什么配置了全局但没生效?可能的原因包括配置类没有被正确扫描到,或者路径匹配的问题。此外,如果同时存在全局配置和局部配置,局部配置会覆盖全局的设置,这点需要注意。 还需要考虑Spring Security的影响。如果项目中引入了Spring Security,可能需要额外的配置,因为Security的过滤器链可能会覆盖CORS设置。这时候需要在Security配置中明确允许CORS,例如调用cors()方法。 另外,测试配置是否生效的方法。可以通过发送预检请求(OPTIONS),查看响应头中是否有Access-Control-Allow-Origin等字段。或者使用Postman、浏览器开发者工具来检查请求和响应头。 总结下来,应该分步骤说明两种主要配置方式,给出示例代码,并提示常见问题和注意事项。同时,可能还需要提到与Spring Security的集成问题,以及测试方法。这样用户可以根据自己的需求选择合适的配置方式,并避免常见的陷阱。</think>为Spring Boot后端应用配置CORS支持请求,可通过以下两种方式实现: --- ### 一、全局配置(推荐) 通过创建配置类实现`WebMvcConfigurer`接口,覆盖`addCorsMappings`方法: ```java import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 匹配所有接口路径 .allowedOrigins("http://localhost:3000") // 允许的前端.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的HTTP方法 .allowedHeaders("*") // 允许所有请求头 .allowCredentials(true) // 允许携带凭证(如Cookie) .maxAge(3600); // 预检请求缓存时间(秒) } } ``` --- ### 二、注解局部配置 在控制器类或方法上使用`@CrossOrigin`注解: ```java @RestController @CrossOrigin(origins = "http://localhost:3000", methods = {RequestMethod.GET, RequestMethod.POST}) public class UserController { @GetMapping("/users") public List<User> getUsers() { // ... } } ``` --- ### 关键配置说明 1. **allowedOrigins** 允许访问的名,支持多个名(`.allowedOrigins("http://a.com", "http://b.com")`)或通配符`"*"`(但`allowCredentials=true`时不可用通配符)[^1] 2. **allowCredentials** 设置为`true`时,前端需显式配置`withCredentials: true`(如Axios) 3. **Spring Security集成** 若项目使用Spring Security,需在配置中启用CORS支持: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors(); // 启用CORS支持 } } ``` --- ### 测试验证 通过浏览器开发者工具检查响应头是否包含: ```http Access-Control-Allow-Origin: http://localhost:3000 Access-Control-Allow-Methods: GET, POST, PUT, DELETE Access-Control-Allow-Credentials: true ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值