小编典典

Ajax请求的CORS错误[重复]

ajax

我在ajax中执行此请求,但是我仍然遇到以下有关CORS的错误:XMLHttpRequest无法加载https://cubber.zendesk.com/api/v2/organizations/37520251/users.json。在飞行前响应中,Access-
Control-Allow-Headers不允许请求标头字段Access-Control-Allow-Origin。您能帮我吗(我看过很多话题,但我仍然不明白为什么它不起作用

 function afficheorga(a){
      $.ajax({
          url: "https://cubber.zendesk.com/api/v2/users/"+a+"/organizations.json",
          type: 'GET',
          dataType: 'json',
          cors: true ,
          contentType:'application/json',
          secure: true,
                    headers: {
                        'Access-Control-Allow-Origin': '*',
                    },
          beforeSend: function (xhr) {
              xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
          },
          success: function (data){
            console.log(data.organizations[0].name);
            var organisation = data.organizations[0].name;
            $("#company").text(organisation);
          }
        })
    }

阅读 1710

收藏
2020-07-26

共1个答案

小编典典

您可以使用来解决此问题jsonp。更改dataType为,jsonp因此您的GET请求应如下

function afficheorga(a){
      $.ajax({
          url: "https://cubber.zendesk.com/api/v2/users/"+a+"/organizations.json",
          type: 'GET',
          dataType: 'jsonp',
          cors: true ,
          contentType:'application/json',
          secure: true,
          headers: {
            'Access-Control-Allow-Origin': '*',
          },
          beforeSend: function (xhr) {
            xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
          },
          success: function (data){
            console.log(data.organizations[0].name);
            var organisation = data.organizations[0].name;
            $("#company").text(organisation);
          }
      })
}
2020-07-26