【发布时间】: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