最近刚好在处理vue与SpringBoot的Rest项目对接,遇到跨域问题,做下笔记记录一下。
下面只是其中一种解决办法
在SpringBoot项目中增加全局配置类WebAppConfigurer
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class WebAppConfigurer {
/**
* 跨域过滤器
*
* @return
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
/**
* 跨域全局配置
* @return
*/
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");//允许所有的请求域名访问我们的跨域资源
corsConfiguration.addAllowedHeader("*");//允许所有的请求header访问,可以自定义设置任意请求头信息
corsConfiguration.addAllowedMethod("*");//允许通过所有的请求方式访问该跨域资源服务器,如:POST
corsConfiguration.setAllowCredentials(true);//要求跨域请求提供凭据信息
return corsConfiguration;
}
}