Azure Machine Learning REST端点前端调用报错:Failed to Fetch
问题与解决方案
我将带有REST端点的Azure机器学习模型部署用于模型消费,用Postman调用该服务完全正常,但通过Codepen搭建的HTML网站用JavaScript调用时,始终返回“Error: Failed to Fetch”错误,Azure Static Web Apps调用也失败。已确认Codepen传入端点的输入参数和Postman完全一致,先后尝试配置CORS、修改请求协议为HTTPS等操作,最终通过调整CORS设置解决了问题。
关键解决要点
- 问题根源是浏览器同源策略限制,前端跨域请求被拦截,核心在于CORS配置不匹配
- 在Azure API Management或Azure ML模型端点的CORS设置中,添加前端实际部署的域名(如Codepen的域名、Azure Static Web Apps的域名)
- 确保CORS规则允许
POST请求方法,同时放行请求中使用的自定义请求头(比如示例中的Ocp-Apim-Subscription-Key) - 务必使用HTTPS协议调用端点,避免浏览器拦截混合内容请求
示例JavaScript代码
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]; const testData = JSON.stringify(formattedData); fetch('https://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 => { const result = data.result[0]; const volumeForecastElement = document.querySelector('#volume-forecast'); volumeForecastElement.textContent = result.join(', '); document.getElementById("result").innerHTML = result; }) .catch(error => { document.getElementById("error").innerHTML = error.message; console.error(error.message) }); });
内容的提问来源于stack exchange,提问作者Ziggy
相关产品推荐
相关产品推荐

