weixin_33743248 2019-04-01 05:46 采纳率: 0%
浏览 54

jQuery ajax中的cors问题[重复]

// find elements
url = 'https://btacertified.com/api/v1/courses';
apitoken = 'RjBMcmlabzZIa3I0bExSM0ZadnN5MFpRNkg5Y3R6UmcyS25uaTFrZVRUcUQ3RUNBVkpHR09LWVNJbklG5c9a7a09c78b6';
var button = $("button")

$(document).ready(function() {
  // handle click and add class
  button.on("click", function() {

    $.ajax({
      url: url,
      type: "POST",
      crossDomain: true,
      data: JSON.stringify({
        "a": 1
      }),
      dataType: "jsonp",
      beforeSend: function(xhr) {
        xhr.withCredentials = true;
      },
      headers: {
        'Access-Control-Allow-Origin': 'https://jsfiddle.net',
        'Authorization': apitoken
      },
      success: function(response) {
        var resp = JSON.parse(response)
        alert(resp.status);
      },
      error: function(xhr, status) {
        alert("error");
      }
    });
  })
});
<!doctype html>
<html lang="en">

<head>
  <title></title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <div id="banner-message">
    <button>Click Me</button>
  </div>
</body>

</html>

I am doing a post API with apitoken authorization in the header to retrieve a json.

I am getting a CORS error, which is "blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header".

P.S: I have checked similar CORS post nothing works for me, I have no control over the 3rd party API server, so I can not add any headers there. Using JSONP i get 405 error

But I can see results via apitest.com in the following link. https://apitester.com/shared/checks/27522c9ca1dc4e7f89fe488f3864909f

</div>
  • 写回答

1条回答 默认 最新

  • 七度&光 2019-04-01 05:58
    关注

    Charlietfl is correct but also, if you know the api can handle CORS requests, you may want to get rid of the access-control-allow-origin from your request (I believe this is a response header) and are you sure you want to set the data type to JSONP? Maybe get rid of this line and let the server decide (most API’s don’t require JSONP nowadays).

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!