我对javascript很陌生。我正在尝试使用XMLHttpRequest从Cisco Meraki的API中获取信息。我没有得到我希望得到的结果,这将是一个组织的名单,我们安装了Meraki设备。我在某个地方读到XMLHttpRequests不适合跨域访问,所以如果我应该使用其他的东西,请告诉我。这也很可能是我有错误的代码,我没有抓住。
我看了大量与API对话的例子,但是没有,我发现如何将一个惟一的API密钥从用户输入传递到get语句到表单中。我在函数底部添加了console.log(),以确保我的变量从调用此函数的html表单中获得值。
以下是运行该函数后在浏览器中看到的错误:
XMLHttpRequest {onreadystatechange:ƒ,readyState: 1,超时: 0,withCredentials: false,upload: XMLHttpRequestUpload,…} addAdmin.php:62 XHR加载失败:选项"https://n159.meraki.com/api/v0/organizations“。listOrgs @ addAdmin.php:62 onclick @ addAdmin.php:43 addAdmin.php:62 XHR加载失败:选项"https://n159.meraki.com/api/v0/organizations“。
这是我的代码:
function listOrgs() {
var apikey = document.getElementById("apikeyinput").value;
var shard = document.getElementById("shardinput").value;
var xhttp, orgData, txt, x, dbParam, fullURL = "";
fullURL = "https://" + shard + ".meraki.com/api/v0/organizations";
xhttp = new XMLHttpRequest();
xhttp.open("GET", fullURL, true);
xhttp.setRequestHeader("Access-Control-Allow-Origin", "Content-Type");
xhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
xhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type, X-
Requested-With");
xhttp.setRequestHeader("X-Cisco-Meraki-API-Key", apikey);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send();
xhttp.onreadystatechange = function writeTable() {
if(this.readyState == 4 && this.status == 200) {
orgData = JSON.parse(this.responseText);
txt += "<table boarder='1'>";
for (x in orgData) {
txt += "<tr><td>" + orgData[x].name + "</td></tr>";
txt += "<tr><td>" + orgData[x].id + "</td></tr>";
};
txt += "</table>"
document.getElementById("printOrgs").innerHTML = txt;
};
}
console.log(fullURL);
console.log(apikey);
console.log(shard);
console.log(xhttp);
}发布于 2018-01-17 13:52:00
你的浏览器抱怨OPTIONS听起来像是飞行前请求失败了。我以前从未使用过这个API,所以我不知道它们是否能解决这个问题,但是这里有一些一般性的提示.
onreadystatechange放在send之前,这样你就没有比赛的条件了。Access-Control-Allow-Origin是一个响应头,而不是一个请求头,它接受一个url作为参数,而不是单词‘content’。把它移开。Access-Control-Allow-Headers也是一个响应头,删除它,并尝试用它的请求头替换它,对应:Access-Control-Request-Headers 在这里读来查看它是如何工作的。Content-Type头告诉hte服务器需要一些JSON数据,但是您没有发送任何东西,更不用说JSO了。这里要做的主要事情是,了解响应头和请求头之间的区别,并确保您知道它们的含义。
https://stackoverflow.com/questions/48302272
复制相似问题