Azure 机器学习 REST 端点 - 无法获取

2024-02-27

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

但是,当我尝试使用 javascript 创建 HTML 网站 (Codepen) 来调用 REST 端点时,我只收到错误:无法获取消息。

我也尝试过使用 Azure Static Web Apps,但也没有成功。

不过,我能够(在控制台中)验证我通过 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]; // Get the result array from the response
            const volumeForecastElement = document.querySelector('#volume-forecast');
            volumeForecastElement.textContent = result.join(', '); // Update the text content of the <b> element with the result array joined by commas
            document.getElementById("result").innerHTML = result;
        })
        .catch(error => {

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

And here is what I get in Postman: enter image description here

update: I added the CORS setting in the Azure API Management and still has the issue: enter image description here

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 enter image description here

It works with Postman though but not with the Javascript: enter image description here

Last Update: Changed CORS again and it now works! enter image description here


正如我的评论中所述,该错误很可能与 CORS 问题有关。

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

您似乎正在使用 API 管理来公开 REST 端点:如果这是正确的,您可以通过定义适当的方法来配置 CORSpolicy https://learn.microsoft.com/en-us/azure/api-management/api-management-policies.

此页面提供有关以下方面的必要信息如何设置或编辑 API 管理策略 https://learn.microsoft.com/en-us/azure/api-management/set-edit-policies?tabs=form.

CORS 政策记录在这另一页 https://learn.microsoft.com/en-us/azure/api-management/cors-policy。该文档提供了示例配置 https://learn.microsoft.com/en-us/azure/api-management/cors-policy#example,适合您的用例:

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

这个相关的SO问题 https://stackoverflow.com/questions/67244072/how-configure-azure-api-management-for-cors也可能有帮助。

此外,请考虑包括Accept header https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept在发布您的信息时,我们遇到了调用 API 管理服务公开的 API 时不存在此标头的问题,我不确定,但我认为默认情况下不包含该标头fetch(与邮递员相反):

fetch('http://ziggyapimanagementservice.azure-api.net/score', {
        method: 'POST',
        headers: {
            'Accept': '*/*',
            '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]; // Get the result array from the response
            const volumeForecastElement = document.querySelector('#volume-forecast');
            volumeForecastElement.textContent = result.join(', '); // Update the text content of the <b> element with the result array joined by commas
            document.getElementById("result").innerHTML = result;
        })
        .catch(error => {

            document.getElementById("error").innerHTML = error.message;
            console.error(error.message)
        });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Azure 机器学习 REST 端点 - 无法获取 的相关文章

随机推荐

  • Android获取JSON键值

    我对解析特定的问题有疑问json细绳 我没有找到任何对我的情况有帮助的东西 我有这个 json AM country name Armenia data 180854 time published 2012 03 30 13 31 39 t
  • 使用 C API 访问 NumPy 数组的视图

    在我用 C 编写的 Python 扩展模块中 我使用以下代码片段将 NumPy 数组转换为犰狳 http arma sourceforge net 用于代码的 C 部分的数组 static arma mat convertPyArrayTo
  • Django 查询集按 ISO 周数过滤

    我有一个模型 其中包含datefield 我正在尝试获取包含本周 从星期一开始 的模型的查询集 所以自从姜戈datefield包含简单的datetime date我假设使用的模型进行过滤 isocalendar 从逻辑上讲 这正是我想要的
  • Date.js parseExact() 当作为数组传入时不解析 4 位数年份

    我是否在 date js 中遗漏了 Date parseExact 的某些内容 根据api文档 我应该能够做到这一点 Date parseExact 10 15 2004 M d yyyy MMMM d yyyy The Date of 1
  • 如何链接 TextView 中的文本以打开网址

    我花了一个多小时查看了大量示例 但没有一个实际上适用于在 TextView 中设置文本以链接到 Web URL 示例代码 text8 TextView findViewById R id textView4 text8 setMovemen
  • 在包含字符串列表的系列上使用 Pandas 字符串方法“包含”

    给定一个简单的 Pandas 系列 其中包含一些可由多个句子组成的字符串 In import pandas as pd s pd Series This is a long text It has multiple sentences Do
  • 将 JSON 对象传递给 MVC 控制器时 string.empty 转换为 null

    我正在将一个对象从客户端传递到服务器 在此过程中 表示为 string empty 的对象属性将转换为 null 我想知道当对象类型支持 string empty 时如何防止这种情况 console log DataToPost dataT
  • 常见爬行-获取WARC文件

    我想使用常见的爬网检索网页 但我迷路了 我想要获取 www example com 的 warc 文件 我看到这个链接 生成以下 json urlkey com example 时间戳 20170820000102 mime text ht
  • 在 Safari iPhone 上的新选项卡中打开链接

    我有一个网站可以帮助人们为 Instagram 帖子创建标题并评估主题标签 其中一项功能非常简单 只需将主题标签链接到 Instagram 即可查看它们包含哪些类型的图像 因为我不希望他们刚刚输入和评估的输入消失 所以我使用 target
  • iOS 获取数组中选定联系人的电子邮件地址

    我想做的就是向用户展示人员选择器 让他选择他想要的所有联系人 最后将所有这些联系人的电子邮件地址放入数组中 最好的办法是只向用户显示带有电子邮件的联系人 到目前为止 我唯一能做的就是向人员选择器提供以下代码 ABPeoplePickerNa
  • 使用 css3 淡入淡出背景图像

    嘿大家 我想知道为什么这行不通 right article boy background transparent url images boxes bg boy jpg left top no repeat width 413px heig
  • 从 .net 向操纵杆发送反馈/效果

    感谢这个答案https stackoverflow com a 13734766 637142 https stackoverflow com a 13734766 637142我能够知道何时按下按钮或何时旋转方向盘 现在我的问题是如何将效
  • 如何解决 mingw32-make.exe 退出并出现代码 2 错误?

    我已经安装了Qt Open source 4 8 3适用于 Windows 的库Windows 8 Pro x64 Qt Creator 2 6 0 and MingW 4 4 0手动 我从 Qt Creator 设置了套件和编译器 我打开
  • 如何使 jQuery `bind` 或 `on` 事件处理程序具有幂等性

    有什么办法可以打电话吗 selector bind click handler or selector on click handler 多次以便处理程序仅附加一次 现在 我有多个具有不同成功回调的 AJAX 处理程序 每个处理程序都会在页
  • ng-class 和 ng-style 有什么区别?

    ng class and ng style两者似乎都是动态设置 CSS 类的方法 它们之间有什么区别 ng style https docs angularjs org api ng directive ngStyle用于将 javascr
  • svn复制命令

    我知道这是一个非常菜鸟的问题 但是当我尝试使用以下命令从现有分支 而不是主干 创建新分支时 svn copy svn ssh svn example com software branches branch name svn ssh svn
  • 将空字符串作为参数传递给 boost::program_options 的最佳方法是什么?

    我有一个程序使用升压 程序选项解析命令行 其中一个参数是 AMQP 交换的名称 并提供默认值 出于测试目的 我想用空字符串覆盖此 AMQP 交换名称 以使用默认交换 我不知道如何将空字符串传递给升压 程序选项 那可能吗 不修改源码 如果没有
  • VS Task Runner Explorer - Node Sass 找不到绑定

    打开 Visual Studio 任务运行程序资源管理器时 gulpfile js加载失败 并且在 输出 窗口中发出此错误 Failed to run C DATA Git MyApp MyBiz MyApp MyBiz MyApp Web
  • 基类与实用类

    两者应该优先选择哪一个 有一些方法由 A B 和 C 类调用 这些方法是否应该封装在 D 类 A B 和 C 的基础 中 OR 是否应该将这些方法封装在类 U 中 并且其他类创建其对象以根据需要使用这些方法 应该在什么基础上做出决定 Tha
  • Azure 机器学习 REST 端点 - 无法获取

    我创建了一个带有 REST 端点的 Azure 机器学习模型作为使用它的方式 当我使用 Postman 运行服务时 一切似乎都工作正常 但是 当我尝试使用 javascript 创建 HTML 网站 Codepen 来调用 REST 端点时