javascript - 错误 - 从 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 策略阻止”错误。关于如何避免它的任何建议?在此先感谢。
解决方案
听起来 API 不是为从前端调用而设计的。您可能需要实现一个调用 API 的后端层。直接从前端使用连接字符串对我来说似乎也有点危险,因为任何访问页面的人都可以看到它并访问 IoT 中心中的所有数据。
推荐阅读
- python - 如何使用 Python 检查虚拟机是否正在运行
- python - 嵌套列表中的递归结果
- json - Swift JSONDecoder 无法使用转义字符解码有效 JSON
- c# - 从排序的字典中获取值的范围
- ios - 如何修复“UITableViewCell 交换数据”?
- html - 为什么将绝对元素定位在其父相对元素的中心,同时将顶部和左侧设置为 50% 不起作用?
- python - 如何创建一个新的 python tkinter 窗口,使其完全适合可用的桌面区域,但没有最大化?
- java - 使用 Java Spring Boot Framework 订阅 STOMP 消息
- javascript - InnerHTML 返回 [object HTMLOptionElement]
- json - 合并数据集生成 Azure 数据工厂管道