一、问题:
在前端使用vue进行调测接口时,发现OPTIONS请求报错,控制台打印Access-Control-Allow-Origin信息,所以基本确定是跨域问题引起的。
二、解决方法(代码如下):
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;
/**
* @author zxw
* @description 运行跨域请求配置类
*/
@Configuration
public class CrossConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许任何域名使用
corsConfiguration.addAllowedOrigin("*");
// 允许任何头
corsConfiguration.addAllowedHeader("*");
// 允许任何方法(POST、GET、OPTIONS等),
// 如果需要限制其他的(HEADER、METHOD等)可以进行设置
//corsConfiguration.setAllowedMethods(Arrays.asList("POST","GET","OPTIONS"));
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 对接口配置跨域设置
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
三、总结:
跨域问题解决的方式有很多种,前端和后台都可以进行解决,再此就不再一一列举,仅提供一种使用有效的方式。