gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:33:45 24 4
gpt4 key购买 nike

我编写了以下 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com