前后端联调的时候,经常会出现跨域问题,也就是出现以下报错:
Access to fetch at 'http://xxxxxxxx:xxxx/uploadExcel' from origin 'http://localhost:xxxx' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
第一种:在controller类上使用@CrossOrigin注解即可,但这只是在controller类上是有效的。
第二种:进行配置
这样即使出现全局异常,后端捕捉并返回给前端的时候,也不会出现跨域问题啦
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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 跨域配置(全局)
* @CrossOrigin 注解只是在控制器上实现的局部跨域
*/
@Configuration
class WebMvcConfiguration implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
/*允许访问的客户端域名*/
corsConfiguration.addAllowedOrigin("*");
/*允许服务端访问的客户端请求头*/
corsConfiguration.addAllowedHeader("*");
/*允许访问的方法名,GET POST等*/
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
如果我的理解有不正确的地方,欢迎指正呦。
因篇幅问题不能全部显示,请点此查看更多更全内容