美文网首页
ajax、fetch跨域访问session丢失问题

ajax、fetch跨域访问session丢失问题

作者: LoWang | 来源:发表于2019-03-04 14:34 被阅读0次

    最近有个版本需要用到跨域请求,在后端已经设置好各种跨域的参数,响应头里面已经ok,但是在跨域提交请求时,发现session会丢失,经过一番查询得知,跨域默认是不会携带cookie等认证数据的,需要在请发起请求时指定参数,让浏览器携带cookie进行请求。

    ajax示例

    原生ajax跨域携带cookie

    var xhr = new XMLHttpRequest();  
    xhr.open("POST", "https://account.scio.com/api/login/v1", true);  
    xhr.withCredentials = true; //支持跨域发送cookies
    xhr.send();
    

    jquery跨域携带cookie

    $.ajax({
        type: "POST",
        url: "https://account.scio.com/api/login/v1",
        dataType: 'jsonp',
        xhrFields: { withCredentials: true },
        crossDomain: true,
    })
    

    fetch示例

    var myHeaders = new Headers();
    fetch('https://account.scio.com/api/login/v1', {
                  method: 'GET',
                  headers: myHeaders,
                  credentials: "include"
                })
    

    spring boot 后端设置

      @Override
      protected void configure(HttpSecurity http) throws Exception {
        http.cors();
     }
    ...
    //直接在指定的方法上使用@CrossOrigin直接
     @CrossOrigin(exposedHeaders = {"_csrf", "X-CSRF-TOKEN"})
     @RequestMapping(
          value = {"/login"},
          method = RequestMethod.HEAD)
    public void headLogin(){
    }
    
    

    相关文章

      网友评论

          本文标题:ajax、fetch跨域访问session丢失问题

          本文链接:https://www.haomeiwen.com/subject/uwqiuqtx.html