首页 > 解决方案 > 错误 - 从 ReactJS 应用程序访问 Azure IOT Hub 时出现“被 CORS 策略阻止”

问题描述

我正在尝试从我的 ReactJS 应用程序连接到 Azure Device twin。我想要完成的是在 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 文件。

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

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

标签: javascriptreactjsazurecorsazure-iot-hub

解决方案


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


推荐阅读