【问题标题】:Error -"Blocked by CORS policy" when accesing Azure IOT Hub from ReactJS application错误 - 从 ReactJS 应用程序访问 Azure IOT Hub 时出现“被 CORS 策略阻止”
【发布时间】:2020-12-01 08:00:33
【问题描述】:

我正在尝试从我的 ReactJS 应用程序连接到 Azure 设备孪生。我想要完成的是在 ReactJS 的 Javascript 环境中从设备中读取报告的数据。这是我正在使用的代码

import React from 'react'
    
 function Greet() {
     const connectionString = '##########';
    
     // The device ID.
     const deviceId = '####';
        
     // The sample connects to service-side endpoint to call direct methods on devices.
     const Client = require('azure-iothub').Client;
     const Registry = require('azure-iothub').Registry;
        
        
     // Connect to the service-side endpoint on your IoT hub.
     const client = Client.fromConnectionString(connectionString);
        
        
     // The sample connects to an IoT hub's Event Hubs-compatible endpoint to read messages sent from a device.
     const { EventHubClient, EventPosition } = require('@azure/event-hubs');
     // const { Console } = require('console');
     // const { stripResponse } = require('@azure/ms-rest-js');
        
     // Locate the device twin via the Registry, then update some tags and properties.
     const registry = Registry.fromConnectionString(connectionString);
        
        
     registry.getTwin(deviceId,function (err, twin) {
         if (err) {
             //redMessage(err.constructor.name + ': ' + err.message);
         } else { 
               
                 console.log("Last received patch: " + twin.properties.reported.Wifi);
                 console.log("Firmware version: " + twin.properties.reported.firmwareVersion);
                 console.log("Fan status: " + twin.properties.reported.fanOn);
                 console.log("Min temperature set: " + twin.properties.reported.minTemperature);
                 console.log("Max temperature set: " + twin.properties.reported.maxTemperature);
               
             }
         });
        
    
     return (
         <h1>helloo</h1>
     )
 }
    
 export default Greet

这是实现代码的 Greet.js 文件。我已经在 app.js 文件中调用了 Greet.js 文件。

当我运行它时,我在控制台中收到一条错误消息。这是错误的屏幕截图。 Screen Shot of error message

我得到的错误是“被 CORS 策略阻止”错误。有关如何避免它的任何建议?在此先感谢。

【问题讨论】:

  • 这实际上不是错误,而是暗示API不喜欢这样调用。您必须检查标题/文档以确定应该如何调用以及从哪些站点调用它
  • 感谢您的帮助。想通了

标签: javascript reactjs azure cors azure-iot-hub


【解决方案1】:

听起来 API 不是为从前端调用而设计的。 您可能需要实现一个调用 API 的后端层。 直接从前端使用连接字符串对我来说似乎也有点危险,因为任何访问页面的人都可以看到它并访问 IoT Hub 中的所有数据。

【讨论】:

  • 你能指导我如何实现一个后端层来调用api吗?我也有问题,因为代码中没有直接的 GET 请求。
  • 建立一个后端是一件相当大的事情,不能短时间解决。您选择您的后端技术(Node.js / Python / Java / .NET / PHP / 其他)并首先开始学习一些教程。
  • 感谢对我帮助很大。在后端实现 GET 请求确实有效。谢谢
猜你喜欢
  • 2021-04-15
  • 2021-03-18
  • 2019-11-01
  • 2021-10-20
  • 2019-08-23
  • 2021-10-16
  • 2019-04-28
  • 2019-12-18
  • 1970-01-01
相关资源
最近更新 更多