前后端分离项目解决跨域请求携带cookie的问题
一、描述:真是一个令人头大的问题,网上百度的大多数方法都是,这样:
前端: withCredentials: true
后端:Access-Control-Allow-Credentials = true;.....
这样做其实也没错,但我这不行,我写的一模一样,可就是不行,o(╥﹏╥)o
最后,我觉得问题可能不在这里,可能是设置cookie的时候除了问题,后来还真是,后来一想,这玩意无非就是 源头->通道->接收,但我一直在整后两个却忽略了源头。
二、案例:以下是解决案例:
1.两个服务:
前端页面放在Nginx服务器,有两个页面:http://localhost:7031/31/31-1.html;http://localhost:7031/31/31-2.html
两个后端,一个放在nginx服务:http://localhost:7032/32/32-1.html 另一个是springboot项目:http://localhost:8080/hello
2.cookie的配置:
function addCookie() {
var exp = new Date();
exp.setTime(exp.getTime() + 60*60*1000);
//错误的cookie设置
document.cookie="cookie31=cookie31" + ";expires=" + exp.toGMTString();
//正确的cookie设置
document.cookie="cookie31=cookie31" + ";expires=" + exp.toGMTString()+";path=/";
}
分析:没有添加path,导致cookie只在当前页面存在,,虽然在application中能看到有存储,但跳转同服务页面时而带cookie,时而不带cookie,跨域请求就更不用想了,不是它不想带,是实在找不到cookie在哪(个人猜测,欢迎大佬解惑)。
从31-1.html,跳转到31-2.html时时而带cookie,时而不带cookie的症状:
01.不带cookie:
02.带cookie:
3.跨域请求携带cookie时,ajax请求需要特殊处理,前端设置:withCredentials: true
//引入在线jquery
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
//js
function goto33() {
$.ajax({
url : "http://localhost:8080/hello",
type: "GET",
crossDomain: true,
xhrFields: {
withCredentials: true
},
success : function(result) {
alert("success");
}
});
4.nginx服务是静态页面,无需处理,springboot项目需要如下配置:
@SpringBootApplication
public class xxApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(xxApplication.class, args);
}
//设置跨域过滤器
private CorsConfiguration corsConfig() {
CorsConfiguration conf = new CorsConfiguration();
conf.addAllowedHeader("*");
conf.addAllowedMethod("*");
conf.addAllowedOrigin("*");
conf.setAllowCredentials(true);
conf.setMaxAge(3600L);
return conf;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfig());
return new CorsFilter(source);
}
}
以上就是心累全过程,资源可以在这里下载:https://download.csdn.net/download/qisoft1213/13124342