zoukankan      html  css  js  c++  java
  • 跨域问题,前端主动向后台发送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

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

  • 相关阅读:
    P1019 单词接龙
    P1219 八皇后
    Find a way
    P1056 排座椅
    P1067 多项式输出
    关于前缀和,A
    洛谷P1223
    洛谷P1803
    洛谷P1208
    常用方法 Excel转换为DataSet
  • 原文地址:https://www.cnblogs.com/demonswang/p/6259966.html
Copyright © 2011-2022 走看看