Azure Machine Learning REST Endpoint – 失败获取

huangapple go评论58阅读模式
英文:

Azure Machine Learning REST Endpoint - Failed to Fetch

问题

我创建了一个带有REST终点的Azure机器学习模型,以便消费它。当我使用Postman运行服务时,一切似乎都正常工作。

然而,当我尝试创建一个HTML网站(Codepen),使用JavaScript调用REST终点时,我只得到一个错误消息:Failed to Fetch。

我还尝试了Azure静态Web应用,但也没有成功。

然而,我能够在控制台中验证,通过Codepen发送到REST终点的输入与Postman中的相同。

这是我的JavaScript示例:

<script>
const form = document.querySelector('#agriculture-form');
form.addEventListener('submit', (event) => {
    event.preventDefault();

    const areaHarvest = parseFloat(document.querySelector('#area-harvest').value);
    const farmGatePrice = parseFloat(document.querySelector('#farm-gate-price').value);
    const volumeOfImport = parseFloat(document.querySelector('#volume-of-import').value);
    const lowTemp = parseFloat(document.querySelector('#low-temp').value);
    const averageTemp = parseFloat(document.querySelector('#average-temp').value);
    const highTemp = parseFloat(document.querySelector('#high-temp').value);
    const precipitationMm = parseFloat(document.querySelector('#precipitation-mm').value);
    const precipitationDays = parseFloat(document.querySelector('#precipitation-days').value);
    const tropicalCyclones = parseFloat(document.querySelector('#tropical-cyclones').value);
    const volumeProductionGuess = 0;

    const data = {
        "Area_Harvested": areaHarvest,
        "FarmGatePricePHPPSA": farmGatePrice,
        "Volume_of_Import": volumeOfImport,
        "temp_low": lowTemp,
        "temp_ave": averageTemp,
        "temp_high": highTemp,
        "precipitation_mm": precipitationMm,
        "precipitation_days": precipitationDays,
        "tropical_cyclone": tropicalCyclones,
        "Volume_of_Production": volumeProductionGuess
    };

    const formattedData = [data];
    console.log('formatted data:', formattedData);
    const testData = JSON.stringify(formattedData);
    console.log('test data:', testData);
    document.getElementById("demo").innerHTML = testData;

    fetch('http://ziggyapimanagementservice.azure-api.net/score', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Ocp-Apim-Subscription-Key': 'cd529cc993494fdfb1530eaf04ae63dc'
        },
        body: testData
    })
        .then(response => response.json())
        .then(data => {
            console.log(data);
            const result = data.result[0]; // 从响应中获取结果数组
            const volumeForecastElement = document.querySelector('#volume-forecast');
            volumeForecastElement.textContent = result.join(', '); // 使用逗号分隔的结果数组更新<b>元素的文本内容
            document.getElementById("result").innerHTML = result;
        })
        .catch(error => {

            document.getElementById("error").innerHTML = error.message;
            console.error(error.message)
        });
});
</script>

这是我在Postman中获得的结果。

英文:

I created an Azure Machine Learning model with a REST Endpoint as a way to consume it. When I run the service using Postman everything seems to work fine.

However, when I try to create an HTML website (Codepen) with a javascript to call the REST Endpoint I only get an Error: Failed to Fetch message.

I also tried with Azure Static Web Apps and I am unsuccessful as well.

I was however able to verify (in the Console) that my input to the Rest Endpoint via Codepen is the same as Postman.

Is there anything I am missing out here?

Here is a sample of my javascript:

&lt;script&gt;
const form = document.querySelector(&#39;#agriculture-form&#39;);
form.addEventListener(&#39;submit&#39;, (event) =&gt; {
event.preventDefault();
const areaHarvest = parseFloat(document.querySelector(&#39;#area-harvest&#39;).value);
const farmGatePrice = parseFloat(document.querySelector(&#39;#farm-gate-price&#39;).value);
const volumeOfImport = parseFloat(document.querySelector(&#39;#volume-of-import&#39;).value);
const lowTemp = parseFloat(document.querySelector(&#39;#low-temp&#39;).value);
const averageTemp = parseFloat(document.querySelector(&#39;#average-temp&#39;).value);
const highTemp = parseFloat(document.querySelector(&#39;#high-temp&#39;).value);
const precipitationMm = parseFloat(document.querySelector(&#39;#precipitation-mm&#39;).value);
const precipitationDays = parseFloat(document.querySelector(&#39;#precipitation-days&#39;).value);
const tropicalCyclones = parseFloat(document.querySelector(&#39;#tropical-cyclones&#39;).value);
const volumeProductionGuess = 0;
const data = {
&quot;Area_Harvested&quot;: areaHarvest,
&quot;FarmGatePricePHPPSA&quot;: farmGatePrice,
&quot;Volume_of_Import&quot;: volumeOfImport,
&quot;temp_low&quot;: lowTemp,
&quot;temp_ave&quot;: averageTemp,
&quot;temp_high&quot;: highTemp,
&quot;precipitation_mm&quot;: precipitationMm,
&quot;precipitation_days&quot;: precipitationDays,
&quot;tropical_cyclone&quot;: tropicalCyclones,
&quot;Volume_of_Production&quot;: volumeProductionGuess
};
const formattedData = [data];
console.log(&#39;formatted data:&#39;, formattedData);
const testData = JSON.stringify(formattedData);
console.log(&#39;test data:&#39;, testData);
document.getElementById(&quot;demo&quot;).innerHTML = testData;
fetch(&#39;http://ziggyapimanagementservice.azure-api.net/score&#39;, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;,
&#39;Ocp-Apim-Subscription-Key&#39;: &#39;cd529cc993494fdfb1530eaf04ae63dc&#39;
},
body: testData
})
.then(response =&gt; response.json())
.then(data =&gt; {
console.log(data);
const result = data.result[0]; // Get the result array from the response
const volumeForecastElement = document.querySelector(&#39;#volume-forecast&#39;);
volumeForecastElement.textContent = result.join(&#39;, &#39;); // Update the text content of the &lt;b&gt; element with the result array joined by commas
document.getElementById(&quot;result&quot;).innerHTML = result;
})
.catch(error =&gt; {
document.getElementById(&quot;error&quot;).innerHTML = error.message;
console.error(error.message)
});
});

</script>

And here is what I get in Postman:
Azure Machine Learning REST Endpoint – 失败获取

update:
I added the CORS setting in the Azure API Management and still has the issue:
Azure Machine Learning REST Endpoint – 失败获取

3-10-2023 update: I added the Accept Header in the Javascript and removed the access key for the moment. Also changed the API to HTTPS just to see if things change.Also changed the CORS value in the API
Azure Machine Learning REST Endpoint – 失败获取

Azure Machine Learning REST Endpoint – 失败获取

It works with Postman though but not with the Javascript:
Azure Machine Learning REST Endpoint – 失败获取

Last Update: Changed CORS again and it now works!
Azure Machine Learning REST Endpoint – 失败获取

答案1

得分: 2

如我的评论中所述,错误很可能与跨域资源共享(CORS)有关。

请考虑配置您的REST端点以发送适用于您的JavaScript应用程序的CORS标头。

您似乎正在使用API管理来暴露REST端点:如果是这样,您可以通过定义适当的策略来配置CORS。

此页面提供了有关如何设置或编辑API管理策略的必要信息。

CORS策略的文档在这个其他页面中有说明。文档提供了适用于您的用例的示例配置

&lt;cors allow-credentials=&quot;true&quot;&gt;
    &lt;allowed-origins&gt;
        &lt;!-- 用于开发的本地主机 --&gt;
        &lt;origin&gt;http://localhost:8080/&lt;/origin&gt;
        &lt;origin&gt;http://your-javascript-app-domain.com/&lt;/origin&gt;
    &lt;/allowed-origins&gt;
    &lt;allowed-methods preflight-result-max-age=&quot;300&quot;&gt;
        &lt;method&gt;POST&lt;/method&gt;
    &lt;/allowed-methods&gt;
    &lt;allowed-headers&gt;
        &lt;header&gt;content-type&lt;/header&gt;
        &lt;header&gt;accept&lt;/header&gt;
    &lt;/allowed-headers&gt;
&lt;/cors&gt;

这个相关的SO问题也可能会有帮助。

此外,请在提交信息时考虑包含一个Accept标头,我们在调用API管理服务暴露的API时遇到了问题,当该标头不存在时,我们经历了问题,我不是绝对确定,但我认为与fetch(与Postman相反)默认不包含它有关:

fetch(&#39;http://ziggyapimanagementservice.azure-api.net/score&#39;, {
        method: &#39;POST&#39;,
        headers: {
            &#39;Accept&#39;: &#39;*/*&#39;,
            &#39;Content-Type&#39;: &#39;application/json&#39;,
            &#39;Ocp-Apim-Subscription-Key&#39;: &#39;cd529cc993494fdfb1530eaf04ae63dc&#39;
        },
        body: testData
    })
        .then(response =&gt; response.json())
        .then(data =&gt; {
            console.log(data);
            const result = data.result[0]; // 从响应中获取结果数组
            const volumeForecastElement = document.querySelector(&#39;#volume-forecast&#39;);
            volumeForecastElement.textContent = result.join(&#39;, &#39;); // 使用逗号分隔的结果数组更新<b>元素的文本内容
            document.getElementById(&quot;result&quot;).innerHTML = result;
        })
        .catch(error =&gt; {

            document.getElementById(&quot;error&quot;).innerHTML = error.message;
            console.error(error.message)
        });
英文:

As stated in my comment, the error could be very likely related to a CORS problem.

Please, consider configuring your REST endpoint for sending the CORS headers appropriate for your Javascript application.

You seem to be using API Management for exposing the REST endpoint: if that is correct, you can configure CORS by defining the appropriate policy.

This page provides the necessary information about how to set or edit API Management policies.

The CORS policy is documented in this other page. The documentation provides a sample configuration, adapted for your use case:

&lt;cors allow-credentials=&quot;true&quot;&gt;
    &lt;allowed-origins&gt;
        &lt;!-- Localhost useful for development --&gt;
        &lt;origin&gt;http://localhost:8080/&lt;/origin&gt;
        &lt;origin&gt;http://your-javascript-app-domain.com/&lt;/origin&gt;
    &lt;/allowed-origins&gt;
    &lt;allowed-methods preflight-result-max-age=&quot;300&quot;&gt;
        &lt;method&gt;POST&lt;/method&gt;
    &lt;/allowed-methods&gt;
    &lt;allowed-headers&gt;
        &lt;header&gt;content-type&lt;/header&gt;
        &lt;header&gt;accept&lt;/header&gt;
    &lt;/allowed-headers&gt;
&lt;/cors&gt;

This related SO question could be of help as well.

Additionally, please, consider including an Accept header when posting your information, we have experienced problems when this header is not present when invoking an API exposed by the API Management service, I am not absolutely sure, but I think it is not included by default by fetch (in contrast to Postman):

fetch(&#39;http://ziggyapimanagementservice.azure-api.net/score&#39;, {
        method: &#39;POST&#39;,
        headers: {
            &#39;Accept&#39;: &#39;*/*&#39;,
            &#39;Content-Type&#39;: &#39;application/json&#39;,
            &#39;Ocp-Apim-Subscription-Key&#39;: &#39;cd529cc993494fdfb1530eaf04ae63dc&#39;
        },
        body: testData
    })
        .then(response =&gt; response.json())
        .then(data =&gt; {
            console.log(data);
            const result = data.result[0]; // Get the result array from the response
            const volumeForecastElement = document.querySelector(&#39;#volume-forecast&#39;);
            volumeForecastElement.textContent = result.join(&#39;, &#39;); // Update the text content of the &lt;b&gt; element with the result array joined by commas
            document.getElementById(&quot;result&quot;).innerHTML = result;
        })
        .catch(error =&gt; {

            document.getElementById(&quot;error&quot;).innerHTML = error.message;
            console.error(error.message)
        });

huangapple
  • 本文由 发表于 2023年2月19日 09:43:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定