到目前为止,我可以告诉我的问题是,我的GET请求未经授权。但是我尝试在报头中添加授权或在URL中添加值(api密钥、用户名、密码)都不成功。
例如:
$.ajax({
type: 'get',
async: false,
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Basic encodedusername:passwordhere');
},
url: "https://api.pingdom.com/api/2.0/checks",
success: function(Data) {
console.log(Data);
},
error: function(Data) {
}
});有没有人能建议我们如何正确使用Javascript语法来与Pingdom API交互?我相信我是在尝试错误地授权,他们的文档集中在PHP上,在这种情况下我无法使用PHP。
https://www.pingdom.com/services/api-documentation-rest/#authentication
发布于 2013-10-19 20:02:07
我不认为在web浏览器中使用Javascript中的Pingdom API是可能的。
您需要使用jsonp让浏览器允许跨站点的ajax请求,但是根据this response的说法,在jsonp请求中设置头部是不可能的。
发布于 2017-05-30 12:47:33
随时随地使用CORS。
我想用一个简单的jQuery请求来检查我们平台上的最后一个Pingdom结果。由于CORS和为身份验证指定自定义标头的需要,这似乎是不可能的。
我不想为这么简单的东西设置代理服务器,所以我找到了,并能够使用CORS Anywhere方法,它看起来像这样:
// Will use the cors-anywhere proxy if jQuery supports it and crossDomain option is passed in.
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
// options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
// Use ajax requests as normal.
$.ajax({
type: 'get',
async: false,
crossDomain: true,
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Basic encodedusername:passwordhere');
},
url: "https://api.pingdom.com/api/2.0/checks",
success: function(Data) {
console.log(Data);
},
error: function(Data) {
}
});备注:如果您正在传递或检索机密信息,请不要使用此选项。如果您正在传递或检索机密信息,则应使用您自己的代理。但是,如果您只是获取公共数据,就像我们一样,那么这应该是一个绕过CORS限制的很好且干净的方法。
https://stackoverflow.com/questions/15947732
复制相似问题