springfilterchain 配置cors
时间: 2023-09-28 16:12:08 浏览: 84
要在Spring中配置CORS(跨源资源共享),你可以使用Spring的`CorsFilter`类。
首先,确保你的项目中已经添加了`spring-web`依赖。然后,在你的Spring配置类中添加以下内容:
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.servlet.Filter;
@Configuration
public class CorsConfig {
@Bean
public Filter corsFilter() {
CorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// 允许的请求来源,可以设置为 * 表示允许所有来源
config.addAllowedOrigin("*");
// 允许的HTTP方法
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
// 允许的请求头
config.addAllowedHeader("Content-Type");
config.addAllowedHeader("Authorization");
// 其他配置,比如允许携带cookies
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
```
这个配置类将创建一个`CorsFilter`实例,并将其注册为一个Bean,使其成为Spring应用程序上下文中的过滤器。`CorsFilter`将根据配置类中的规则处理CORS请求。
在上述示例中,允许所有来源的请求,允许的HTTP方法包括GET、POST、PUT和DELETE。你可以根据需要添加或移除允许的方法。此外,`addAllowedHeader`用于添加允许的请求头。
你还可以根据需要添加其他配置,比如允许携带cookies等等。
请注意,这是一种基本的CORS配置,可能不适用于所有情况。根据你的需求,你可能需要进行更多的定制化配置。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)