跨源资源共享CORS说明:link
问题:跨域限制
问题描述:已拦截跨源请求:同源策略禁止读取位于 http://localhost:6060/api/sys/login 的远程资源。(原因:CORS 头缺少 ‘Access-Control-Allow-Origin’)。
问题分析:这是一种跨域问题。访问的域名和端口和原来的请求不同,请求就会被限制
SOLVE:给网关添加一个cors配置filter,将所有请求在返回时添加对应允许所要请求跨域的CORS响应头
@Configuration
public class GulimallCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1、配置跨域
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
配置完跨域后,点击登录发现竟然有重复:
因为已经在网关中统一配置过跨域,需要将renren-fast项目的“io.renren.config.CorsConfig”类注释掉
PS:非简单请求, 需要OPTIONS方法先发起一个预检请求到服务器,以获知服务器是否允许该实际请求