无法在JavaScript中调用api(交叉源)

时间:2014-08-12 07:03:27

标签: javascript jquery cors smartsheet-api smartsheet-api-1.1

我编写了以下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)请求。我使用here中的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. 

我是朝着正确的方向前进的吗?我该如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:1)

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