解决跨域- (一)使用nginx部署为同一域
静态请求 http://nginx/xxx
动态请求 http://nginx/api/xxx
在filter上统一添加配置
在模块中添加CorsConifguration配置
package com.atguigu.gulimall.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
@Configuration
public class GulimallCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1、配置跨域
//允许哪些请求头跨域
corsConfiguration.addAllowedHeader("*");
//允许哪些请求方式跨域
corsConfiguration.addAllowedMethod("*");
//因为springboot2.4以后
//setAllowCredentials和addAllowedOrigin冲突,所以换成addAllowedOriginPattern配置
corsConfiguration.addAllowedOriginPattern("*");
//允许哪些请求来源跨域
// corsConfiguration.addAllowedOrigin("*");
//允许携带Cookie跨域
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsWebFilter(source);
}
}