Error message "Blocked by CORS policy" when accessing IOT hub from React application

Senuda Jayalath 41 Reputation points
2020-12-01T06:53:22.463+00:00

I have been trying to publish and subscribe to device twins from my backend app in React JS.

This is the React JS code to get reported properties

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  

But when I run this I get the error below on my console
43800-capture2.png

How should i solve this problem.

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,112 questions
{count} votes

Accepted answer
  1. Matthijs van der Veer 4,376 Reputation points MVP
    2020-12-01T07:36:41.447+00:00

    IoT Hub doesn't currently support Cross-Origin Resource Sharing (CORS), this means you won't be able to call this endpoint from your browser. You'll have to create some kind of proxy to do this. You could build a Node.js backend for instance and let that do the API call instead.

    0 comments No comments

0 additional answers

Sort by: Most helpful