• 跨域问题,前端主动向后台发送cookie


    跨域是什么?

    从一个域名的网页访问另一个域名的资源,就会出现跨域。只要协议、端口、域名有一个不同就会出现跨域

    例如:

    1.协议不同  http://www.baidu.com:80 和 https://www.baidu.com:80

    2.端口不同  https://www.badu.com:80 和 https://www.baidu.com:8888

    3.域名不同 https://www.jd.com:80 和 https://www.taobao.com:80

    当浏览器向后台发起请求时,如果是跨域请求,那么就不会发送cookie给后台,而cookie中有一些信息,例如JsessionID等身份信息就不能发送给后台,这样会导致服务器认为你没有登录。

    而如果前台已经解决了主动发送cookie的问题,后台如果header中没有“Access-Control-Allow-Origin”,并且值为*或者浏览器当前访问网页的域名时,那么会直接进入ajax的error方法中,浏览器会直接将返回的内容丢掉。
    解决方案:

    前端:

    1.jquery ajax

    $.ajax({

    url: '自己要请求的url',
    method:'请求方式', //GET POST PUT DELETE
    xhrFields:{withCredentials:true},
    success:function(data){
    //自定义请求成功做什么
    },
    error:function(){
    //自定义请求失败做什么
    }

    })

     2.angular.js

    $http.get(url, {withCredentials: true});
    $http.post(url,data, {withCredentials: true});
    后台:java spring
    response().setHeader("Access-Control-Allow-Credentials", "true");
    response().setHeader("Access-Control-Allow-Origin", "login.com");

    注意,这里login.com 不能设置为 * 来允许全部,如果在 Credentials 是true 的情况下。因为浏览器会报错如下:
    A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://10.0.0.3:18080' is therefore not allowed access

     所以要设置成客户端页面的 域名。

  • 相关阅读:
    Spring-data-jpa和mybatis的比较及两者的优缺点?
    http和https的区别
    Springboot中spring-data-jpa实现拦截器
    RabbitMQ客户端页面认识
    设计模式之策略模式
    设计模式之策略模式应用实例(Spring Boot 如何干掉 if else)
    设计模式之装饰器模式
    网页跳转小程序
    好帖子
    git 回滚操作
  • 原文地址:https://www.cnblogs.com/demonswang/p/6259966.html
Copyright © 2020-2023  润新知