1. 程式人生 > >Spring Cloud (6) | spring cloud zuul 跨域問題No 'Access-Control-Allow-Origin' header

Spring Cloud (6) | spring cloud zuul 跨域問題No 'Access-Control-Allow-Origin' header

在用spring cloud zuul做Filter的時候,訪問微服務出現跨域問題,在網上找了很多辦法:

zuul:
  ignored-headers: Access-Control-Allow-Credentials, Access-Control-Allow-Origin

方法1
於是在Filter裡面改程式碼解決了問題:
CloudFilter.java

@Component
public class CloudFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return
"pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletResponse response = ctx.getResponse(); response.addHeader("Access-Control-Allow-Origin"
, "*"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); } }

方法2
在@EnableZuulProxy註解裡的Class類加入下面這個Bean:
用到CorsFilter這個類,需要import org.springframework.web.filter.CorsFilter;

    @Bean
public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("HEAD"); config.addAllowedMethod("GET"); config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("PATCH"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); }

更多系列文章推薦: