前後端分離-服務端解決跨域問題引入網關之坑。

如果採用服務端解決跨域問題,一般做法是在application類中的filter中添加如下代碼:

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

那如果引入GetWay網關,並且在網關的filter中也假如解決跨域問題代碼,那麼在http服務請求時就會報如下問題:

    The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. 

查看http請求發現,response header 中的參數均是返回兩遍。如下:



導致此現象的問題是我們web請求是通過GetWay代理轉發,這樣網關和api服務均解決跨域問題,導致重複返回。因此,如果服務是通過網關代理那麼服務裏就不要添加跨域問題代碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章