无法在JavaScript中调用api(跨源)

Unable to call an api in JavaScript (cross origin)

本文关键字:api 跨源 调用 JavaScript      更新时间:2023-09-26

我写了下面的JavaScript来调用Smartsheet API:

$.get( "https://api.smartsheet.com/1.1/users/sheets", "Authorization: Bearer [My Access token]" )
.done(function( data ) {
    alert( "Data Loaded: " + data );
});

但是这抛出了以下错误:

XMLHttpRequest cannot load https://api.smartsheet.com/1.1/users/sheets?Authorization:%20Bearer%[My Access token]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

阅读后,我意识到代码必须发出跨域资源共享(CORS)请求。我在这里使用jQuery编写了以下代码:

function createCORSRequest(method, url) {
      var xhr = new XMLHttpRequest();
      if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
      } else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
      } else {
        xhr = null;
      }
      alert("cors created");
      return xhr;
}
var xhr = createCORSRequest('GET', "https://api.smartsheet.com/1.1/users/sheets?Authorization=Bearer+[My Access token]");
if (!xhr) {
    throw new Error('CORS not supported');
}
xhr.onload = function() {
    var text = xhr.responseText;
    alert('Response from CORS request: ' + text);
};
xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
};
xhr.send();
但是,这再次在浏览器控制台中产生相同的错误:
XMLHttpRequest cannot load https://api.smartsheet.com/1.1/users/sheets?Authorization=Bearer+[My Access token]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

我走的方向对吗?我如何解决这个问题?

谢谢。

正如在评论中提到的,Smartsheet API目前不支持CORS。