SpringBoot和Cloud 解决跨域问题方法

一、SpringBoot

增加类CORSFilter

@Configuration

@Order(Ordered.HIGHEST_PRECEDENCE)

public class CORSFilterimplements Filter {

  private FilterConfigconfig;

  public static final StringCREDENTIALS_NAME ="Access-Control-Allow-Credentials";

  public static final StringORIGIN_NAME ="Access-Control-Allow-Origin";

  public static final StringMETHODS_NAME ="Access-Control-Allow-Methods";

  public static final StringHEADERS_NAME ="Access-Control-Allow-Headers";

  public static final StringMAX_AGE_NAME ="Access-Control-Max-Age";

  @Override

    public void destroy() {

  }

  @Override

  public void doFilter(ServletRequest req, ServletResponse resp,

                    FilterChain chain)throws IOException, ServletException {

    HttpServletResponse response = (HttpServletResponse) resp;

    HttpServletRequest request = (HttpServletRequest) req;

    response.setHeader("Access-Control-Allow-Origin", "*");

    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

    response.setHeader("Access-Control-Max-Age", "3600");

    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type,        Authorization, credential, X-XSRF-TOKEN");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {

      response.setStatus(HttpServletResponse.SC_OK);

    }else {

      chain.doFilter(req, resp);

    }

}

@Override

 public void init(FilterConfig filterConfig)throws ServletException {

    config = filterConfig;

 }

}

二、SpringCloud

在Gate Application中增加

@Bean

public CorsFiltercorsFilter() {

final UrlBasedCorsConfigurationSource source =new UrlBasedCorsConfigurationSource();

  final CorsConfiguration config =new CorsConfiguration();

  config.setAllowCredentials(true); // 允许cookies跨域

  config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin

  config.addAllowedHeader("*");// #允许访问的头信息,*表示全部

  config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了

  config.addAllowedMethod("OPTIONS");// 允许提交请求的方法,*表示全部允许

  config.addAllowedMethod("HEAD");

  config.addAllowedMethod("GET");// 允许Get的请求方法

  config.addAllowedMethod("PUT");

  config.addAllowedMethod("POST");

  config.addAllowedMethod("DELETE");

  config.addAllowedMethod("PATCH");

  source.registerCorsConfiguration("/**", config);

  return new CorsFilter(source);

}

你可能感兴趣的:(SpringBoot和Cloud 解决跨域问题方法)