攜帶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就會被帶上去請求數據了。。。  
相關文章
相關標籤/搜索