renren-fast configures the processing configuration class for cross-domain requests in io.renren.config.CorsConfig
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
}
However, after the gateway is configured, this part of the cross-domain settings will not take effect.
This cross-domain setting should only take effect when the service is accessed directly, that is,
Browser——"Send a pre-check request to the service such as localhost:8000——The service detects a cross-domain request, processes the request according to the configuration of the above code and responds—"The browser receives the service to allow cross-domain, and sends the real request
But after setting up the gateway, if the gateway is not configured cross-domain
Browser——"Send a pre-check request to the gateway——"The gateway is not configured with cross-domain, cross-domain requests are not allowed—"The server does not send the real request
After configuring the cross domain of the gateway
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
CorsConfiguration configuration=new CorsConfiguration();
//1 配置跨域
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.addAllowedOriginPattern("*");
configuration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",configuration);
return new CorsWebFilter(source);
}
it becomes
Browser——"Send pre-check request to gateway—"Gateway configures cross-domain, filter processes request header, adds allowed cross-domain part—"Service discovers cross-domain, handles allowed cross-domain part—"Returns to browser,
At this point, there will be a problem that the response header is configured twice, and the response header is as follows
Access-Control-Allow-Credentials: true
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8001
Access-Control-Allow-Origin: http://localhost:8001
Content-Type: application/json
Date: Wed, 09 Nov 2022 03:16:40 GMT
transfer-encoding: chunked
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
The error is as follows
:8001/#/login:1
Access to XMLHttpRequest at 'http://localhost:88/api/sys/login' from origin 'http://localhost:8001' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8001, http://localhost:8001', but only one is allowed.
So when using a gateway, all services should not configure cross-domain settings themselves