SpringBoot跨域时从不同的页面发送ajax请求得到的session不是同一个问题解决
html页面发送ajax请求时加上该条参数:
xhrFields: {
withCredentials: true
},
上篇博客说的,@CrossOrigin实现跨域请求的这个注解现在不需要了。
统一该为改为在配置类中定义一个过滤器
注释应该都看得懂,就不详细说了
具体实现为:
package top.yibobo.hospital.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
private static String[] orgins = new String[]{
"localhost:8080",
"127.0.0.1"
};
@Bean
public CorsFilter corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//跨域请求访问配置
CorsConfiguration configuration = new CorsConfiguration();
for (String url:orgins){
configuration.addAllowedOrigin("http://"+url);
configuration.addAllowedOrigin("https://"+url);
}
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");//请求方法限制:如GET/POST,*表示所有都允许
configuration.setAllowCredentials(true);
//对当前这个服务器下所有有的请求都启用这个配置
source.registerCorsConfiguration("/**",configuration);
return new CorsFilter(source);
}
}