问题描述
SpringCloudGateWay中跨域配置不起作用
使用filter
@Component public class CORSFilter implements Filter{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; res.addHeader("Access-Control-Allow-Credentials", "true"); res.addHeader("Access-Control-Allow-Origin", "*"); res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN"); if (((HttpServletRequest) request).getMethod().equals(HttpMethod.OPTIONS)) { response.getWriter().println("ok"); return; } chain.doFilter(request, response); } }
使用注解
自定义filter
@Configuration public class CORSFilter{ @Bean public CorsFilter corsFilter(){ CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowCredentials(true); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addExposedHeader("*"); UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource(); corsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration); //3. 返回新的CorsFilter return new CorsFilter(corsConfigurationSource); } }
原因分析:
SpringCloudGetway是Springwebflux的而不是SpringWebMvc的,所以我们需要导入的包导入错了
解决方案:
正确导包