zoukankan      html  css  js  c++  java
  • 携带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就会被带上去请求数据了。。。  
  • 相关阅读:
    jQuery对表单的操作
    js-工厂模式
    js中call、apply、bind的区别
    js实现重载和重写
    js封装/继承/多态
    变量的解构赋值
    var & let & const 的区别
    jQuery之animate中的queue
    jQuery之动画
    .trigger
  • 原文地址:https://www.cnblogs.com/zhuotiabo/p/6230521.html
Copyright © 2011-2022 走看看