CORS跨域请求配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//addAllowedOrigin:设置访问源地址
corsConfiguration.addAllowedOrigin("*");
//addAllowedHeader:设置访问源请求头
corsConfiguration.addAllowedHeader("*");
//addAllowedMethod:设置访问源请求方法
corsConfiguration.addAllowedMethod("*");
//GET:请求指定的页面信息,并返回实体主体
/*corsConfiguration.addAllowedMethod(HttpMethod.GET);*/
//HEAD:类似于GET请求,只不过返回的响应中没有具体的内容,用于获取报头
/*corsConfiguration.addAllowedMethod(HttpMethod.HEAD);*/
//POST:向指定资源提交数据进行处理请求,数据被包含在请求体中
/*corsConfiguration.addAllowedMethod(HttpMethod.POST);*/
//PUT:从客户端向服务器端传送的数据取代指定的文档内容
/*corsConfiguration.addAllowedMethod(HttpMethod.PUT);*/
//PATCH:用于对资源进行部分修改
/*corsConfiguration.addAllowedMethod(HttpMethod.PATCH);*/
//DELETE:请求服务器删除指定页面
/*corsConfiguration.addAllowedMethod(HttpMethod.DELETE);*/
//OPTIONS:允许客户端查看服务器的性能
/*corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);*/
//TRACE:回显服务器收到的请求,主要用于测试或诊断
/*corsConfiguration.addAllowedMethod(HttpMethod.TRACE);*/
//setMaxAge:设置跨域请求最大有效时长,单位:秒
corsConfiguration.setMaxAge(3600L);
//setAllowCredentials:是否支持Cookie
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}