携带cookie进行数据请求

时间:2023-03-10 05:20:11
携带cookie进行数据请求

前端进行数据请求有:普通的ajax(json)请求,jsop跨域请求,cors跨域请求,fetch请求...PC端这些请求方式中,普通的ajax(json)请求和jsop跨域请求是默认携带cookie的,而cors跨域请求和fetch请求默认是不携带cookie的。因此,当我们的请求需要携带cookie时,我们就要对cors跨域请求和fetch请求这两中请求方式进行特殊配置处理。对于做移动端的童鞋来说,要是能把项目运行在PC端中最好不过,对于调试过程中的BUG一目了然,所以做特殊处理后更有利于我们在PC端进行调试。

  • fetch请求方式:
    fetch('/community/getCommunityActivityByCommunityId', {
    method: "POST",
    headers: {
    "Content-Type": "application/x-www-form-urlencoded"
    },
    credentials: 'include',
    body:"communityId="+this.props.location.query.communityId
    })
    .then((res) => { return res.json(); })
    .then((data) => {
    //请求成功
    })
    .catch((e) => {
    //报错
        });
    1. 我们要在请求头中添加上这个配置:
      credentials: 'include'
  • cors跨域请求方式:
    $.ajax({
    type: "post",
    url:"/activity/queryPrizeRecord",
    dataType: "json",
       xhrFields: {
    withCredentials: true
    },
    crossDomain: true,
    data:{},
    success:function(data){ },
    error:function(e){
    }
    })
    1. 我们要在请求头中添加上这个配置:
        xhrFields: {
      withCredentials: true
      },
      crossDomain: true
  • 配上对应的特殊配置后,cookie就会被带上去请求数据了。。。