前后端分离项目解决跨域请求携带cookie的问题

前后端分离项目解决跨域请求携带cookie的问题

一、描述:真是一个令人头大的问题,网上百度的大多数方法都是,这样:

前端: withCredentials: true

后端:Access-Control-Allow-Credentials = true;.....

这样做其实也没错,但我这不行,我写的一模一样,可就是不行,o(╥﹏╥)o

最后,我觉得问题可能不在这里,可能是设置cookie的时候除了问题,后来还真是,后来一想,这玩意无非就是 源头->通道->接收,但我一直在整后两个却忽略了源头。

二、案例:以下是解决案例:

      1.两个服务:

前端页面放在Nginx服务器,有两个页面:http://localhost:7031/31/31-1.htmlhttp://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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值