Azure 计费 API JavaScript 返回 CORS 错误,但在使用邮递员时不会返回



我现在不知所措。我正在尝试通过我的php应用程序访问Azure计费和使用情况API,但不断收到以下错误:

XMLHttpRequest 无法加载 https://ea.azure.com/rest/{协议编号}/使用情况报告。对 预检请求未通过访问控制检查:否 "访问控制允许源"标头存在于请求的上 资源。因此,不允许访问源"http://localhost"。

我知道链接提到 url 是 https://consumption.azure.com/v2/enrollments,但这对我不起作用,在与 Azure 技术服务联系后,我需要使用较旧的 ea.azure.com 入口点。

我正在从我的开发 xampp 本地主机服务器以及生产服务器(实时内联网解决方案(中尝试这样做,但无济于事。使用邮递员连接成功,我收到来自 API 的有效响应。

基本上,API 只需要一个 API 密钥,我有一个。 旁边不需要授权。

由于 Postman 成功地从 API 获得有效的响应,我使用他们的代码生成器来获取我:

  • PHP 脚本
  • JavaScript 脚本
  • jquery ajax script

它们都为我返回相同的错误;显示jquery ajax是因为它是首选的:

var settings = {
"async": true,
"crossDomain": true,
"url": "https://ea.azure.com/rest/<?php echo $agreement_number; ?>/usage-reports",
"method": "GET",
"dataType": 'json',
"headers": {
"authorization": "bearer <?php echo $key; ?>"
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connected.n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.n' + jqXHR.responseText;
}
console.log(msg);
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});

我不明白为什么 Postman 能够连接到 API 并检索它的信息,而完全相同的代码在我的应用程序中使用时会产生 CORS 错误。

这可能与我的应用程序托管在公司网络的内部虚拟机中有关,无法从 Internet 访问?

编辑:Rory提到了JS的严格安全限制 - 因此我也添加了php脚本。由于我使用 php 5.6,默认情况下我没有 httpRequest 类,所以我使用 twslankard 的 httpRequest 类并对其进行调整以接受这样的自定义标头(添加了公共函数(:

public function setHeaders($headers) {
if(is_array($headers)) {
foreach($headers as $name => $val) {
$this->headers[$name] = $val;
}
}

}

并像这样调用类:

include_once($_SERVER['DOCUMENT_ROOT'].'/functions/class_httprequest.php');
$request = new HttpRequest($url, 'GET');
$request->setHeaders(array(
'api-version' => '2014-09-02',
'authorization' => $key
));
try {
$response = $request->send();
echo $request->getStatus().'<br>';
echo $request->getResponseBody();
} catch (HttpException $ex) {
echo $ex;
}

使用 php版本它确实有效,诀窍是添加 api-version 标头,在此之前,我使用 php 脚本返回了 http 400 错误。

使用 php版本它确实有效,诀窍是添加 api-version 标头,在此之前我使用 php 脚本返回 http 400 错误。

相关内容

最新更新