2016-12-04 36 views
0

我有一個使用Zuul Netflix公司作爲API網關的應用程序,該架構如下:如何使用CORS在Zuul工作作爲API網關+ AngularJS +微服務

enter image description here

的架構做工精細,用瀏覽器和郵遞員我可以從微服務(服務1,2和3)訪問不同的REST端點。但是,當我嘗試在我的前端Web應用程序(AngularJS WebApp)中使用它時,它在Chrome控制檯中給我提供了以下錯誤。

XMLHttpRequest cannot load http://localhost:8080/person/api/all. Response for preflight is invalid (redirect) 

通過自己的地址和端口使用該服務將工作,如果我將@CrossOrigin註解。但是,當通過網關訪問它時,其他端點上的註釋不會起作用@CrossOrigin

試圖在我的安全配置中創建下面的過濾器,但仍然無法正常工作,而是在Chrome控制檯中出現下面的錯誤。

@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); 
    } 

瀏覽器控制檯(鉻)...

XMLHttpRequest cannot load http://localhost:8080/person/api/all. Redirect from 'http://localhost:80/person/api/all' to 'http://localhost:80' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect. 

下面是示例AngularJS HTTP請求。

app.controller('loginCtrl', [ 
    '$scope', '$http', function($scope, $http) { 

     $http.get('http://localhost:8080/person/api/all').then(function(data) { 
     return console.log(data.data); 
     }); 
]); 

有人知道如何處理它嗎?很多教程在這裏和那裏,但他們的webapp也是一個春季啓動應用程序,無論是在api網關中選擇,還是使用@EnableZuulProxy註釋來分開,這不是我想要的。

如果有人能提供幫助,請提前致謝。

回答

1

採用類似的架構,面臨着類似的問題,我沒有作以下修改和工作對我來說:

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); 

config.setAllowCredentials(true); 
config.addAllowedOrigin("*"); 
config.addAllowedHeader("*"); 
config.addAllowedMethod("*"); 
source.registerCorsConfiguration("*", config); 

,並在我的角度http請求我加了頭,

{'Access-Control-Allow-Origin':'*'} 

爲我工作。

我試圖在原來的情況下,我只能訪問在Zuul路由映射中映射的第一個URL。但在替換/ **之後*能夠訪問所有映射而沒有問題,同樣與Angular一樣,所有的請求都應該包含頭文件。 我對這個問題也很陌生,可能稍後我會有更多的信息和細節,現在我可以說它對我有用,希望它也適用於你。