URL: http://localhost:8080/**
协议(http)、 域名(localhost)、 端口号(8080);若url 三者有一不同,就违背同源策略。
1、在Controller类上加注解@CrossOrigin(maxAge = 3600)
2.CorsFilter过滤器
package com.atguigu.gulimallgateway.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.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
/**
* User: ldj
* Date: 2022/7/21
* Time: 1:12
* Description: 统一网关配置
*/
@Configuration
public class WebCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter() {
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//配置跨域
corsConfiguration.addAllowedHeader("*"); //允许任意请求头跨域
corsConfiguration.addAllowedMethod("*"); //允许任何请求方式跨域
corsConfiguration.addAllowedOrigin("*"); //允许任意请求来源跨域
corsConfiguration.setAllowCredentials(true); //允许携带cookie信息跨域
corsConfiguration.setMaxAge(3600L); //准备响应前的缓存持续的最大时间(以秒为单位)
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(urlBasedCorsConfigurationSource);
}
}
3.实现WebMvcConfigurer接口
package com.atguigu.gulimallgateway.config;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* User: ldj
* Date: 2022/7/21
* Time: 3:24
* Description: 这是一种全局支持跨域的方法
*/
public class WebCorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("*")
.allowCredentials(true)
.maxAge(3600);
}
}
后续补充:
使用 Nginx 代理转发,监听前端的端口