前端通過瀏覽器調后端服務RESTFul接口,報錯如下圖:
現象:
響應頭信息重復,如下圖,但是用postman調接口響應是正常的。
原因:
是由於項目中設置了雙跨域配置導致的問題。一層是網關服務中包含跨域配置,另一層是服務中設置了跨域配置。
配置如下代碼:
package com.xxx.gateway.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.setMaxAge(3600L); corsConfiguration.addAllowedMethod(HttpMethod.POST); corsConfiguration.addAllowedMethod(HttpMethod.GET); corsConfiguration.addAllowedMethod(HttpMethod.DELETE); corsConfiguration.addAllowedMethod(HttpMethod.PUT); corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS); corsConfiguration.setAllowCredentials(true); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } }
解決方法:
既然我們知道了出現問題的原因,那解決辦法很簡單,就是去掉一層跨域設置。在這里我去掉了服務中的跨域配置(保留網關的跨域設置)