springboot解决跨域配置类
时间: 2023-11-04 20:32:41 浏览: 49
Spring Boot提供了一种简单的方式来解决跨域问题,只需在application.properties文件中添加以下配置即可:
server.cors.enabled=true
server.cors.allowed-origins=*
server.cors.allowed-methods=GET,PUT,POST,DELETE,OPTIONS
server.cors.allowed-headers=*
相关问题
springboot解决跨域问题怎么配置
SpringBoot可通过使用Filter来解决跨域问题,只需要在SpringBoot的配置类中添加如下代码即可:FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new CorsFilter(corsConfigurationSource)); registrationBean.setOrder(0); registrationBean.setName("CorsFilter"); registrationBean.addUrlPatterns("/*"); return registrationBean;
SpringBoot跨域配置类
在SpringBoot中,可以通过配置类来实现跨域请求。以下是一个示例:
```java
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
};
}
}
```
在上面的代码中,我们创建了一个名为`CorsConfig`的配置类,它使用了`@Configuration`注解,表明这是一个SpringBoot的配置类。
我们还使用了`@Bean`注解来声明一个名为`corsConfigurer`的Bean,它返回了一个`WebMvcConfigurerAdapter`对象。
在`WebMvcConfigurerAdapter`对象中,我们重写了`addCorsMappings`方法,这个方法用于配置跨域请求。在这个方法中,我们使用了`CorsRegistry`对象来定义跨域请求的参数。
在上面的代码中,我们允许所有来源(`allowedOrigins("*")`)的请求,支持GET、POST、PUT和DELETE请求(`allowedMethods("GET", "POST", "PUT", "DELETE")`),允许所有的头文件(`allowedHeaders("*")`),并支持跨域请求的Cookie(`allowCredentials(true)`)。我们还设置了跨域请求的最大缓存时间为3600秒(`maxAge(3600)`)。
完成了以上配置后,我们就可以在我们的SpringBoot应用程序中使用跨域请求了。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)