Search code examples
javascriptreactjsazurecorsazure-iot-hub

Error -"Blocked by CORS policy" when accesing Azure IOT Hub from ReactJS application


I am trying to connect to Azure Device twin from my ReactJS app. What I want to accomplish is to read the reported data from the device in Javascript environment in ReactJS. This is the code I am using

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

This is the Greet.js file where the code gets implemented. I have called the Greet.js file in the app.js file.

When I run this I get a error message in the console. This is a screenshot of the error. Screen Shot of error message

The error Iam getting is "Blocked by CORS Policy" Error. Any suggestions on how to avoid it ?Thanks in advance.


Solution

  • Sounds like the API is not designed to be called from the front-end. You may need to implement a back-end layer that calls the API instead. Using the connection string directly from the front-end seems a little dangerous to me as well, as anyone visiting page can see it and access all data in the IoT Hub.