业务场景
VUE请求后端,后端配置了shiro权限拦截,重定向到/noAuth地址,返回给前端后,前端发生跨域问题,Access to XMLHttpRequest at ‘http://localhost:8080/noAuth’ (redirected from ‘http://localhost:8080/xxx/yyyy/zzzz’) from origin ‘http://localhost:8088’ has been blocked by CORS ploicy:Response to prefilight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
解决方案
后台增加跨域配置
@Component
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrign("http://localhost:8088");//允许哪些网站跨域请求 "*"允许所有网站
configuration.addAllowedHeader("*");//允许在请求头中携带的头信息
configuration.addAllowedMethod("*");//允许跨域的ajax的请求方式"GET" "POST" "DELETE" "PUT" "OPTIONS"
configuration.setMaxAge(3600L);//本次跨域检测的有效期
configuration.setAllowCredentials(true);//是否允许携带cookie
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/noAuth", configuration);
//source.registerCorsConfiguration("/**", configuration);
return new CorsFilter(source);
}
}