springboot的yaml配置跨域
时间: 2023-07-02 20:14:58 浏览: 79
要在Spring Boot中启用跨域资源共享(CORS),您可以使用Spring框架提供的CorsFilter类或使用自定义过滤器。
在application.yaml文件中添加以下配置来启用CorsFilter:
```yaml
spring:
cors:
allowed-origins: "*"
allowed-methods: "GET, POST, PUT, DELETE, OPTIONS"
allowed-headers: "Authorization, Content-Type"
allow-credentials: true
max-age: 3600
```
- allowed-origins: 允许的来源,"*"表示所有来源。
- allowed-methods: 允许的请求方法。
- allowed-headers: 允许的请求头。
- allow-credentials: 是否允许发送cookie。
- max-age: 预检请求的有效期。
如果您想使用自定义过滤器,可以在配置类中创建一个@Bean方法来创建该过滤器并将其添加到过滤器链中:
```java
@Configuration
public class WebConfig {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
config.setAllowCredentials(true);
config.setMaxAge(3600L);
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}
```
这将创建一个名为corsFilter的过滤器,并将其添加到过滤器链中,以便在处理请求之前进行CORS检查。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)
![](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)
![](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)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)