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

标签 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. 

我的方向是否正确?我该如何解决这个问题?

谢谢。

最佳答案

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

关于javascript - 无法在 JavaScript 中调用 api(跨源),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25258117/

相关文章:

jquery - 将背景颜色过渡到偏移位置

javascript - 使用 Angular 和 Node 的 Oauth

php - Javascript 时间转换为 PHP 时间

javascript - jquery datepicker 设置 mindate

javascript - 如何将 Angular 应用程序中的对象数组从一个组件传递到另一个组件

Jquery AJAX删除问题

javascript - ReactJS 没有 'Access-Control-Allow-Origin'

javascript - 无法使用内容类型 : application/json from angular to rails 进行 POST

javascript - 尝试使用 filter() 从节点获取文本,但返回一个对象?

javascript - Ace 编辑器 JavaScript : How to disable all extra commands that aren't default in textarea?