Search code examples
node.jsapicorscreate-react-app

CORS Error when fetching data from Zoho API on React frontend


The company I work at makes use of Biometric attendance, and syncs the data up to Zoho servers for record keeping. I tried to develop a web-app making use of the Zoho People API, which lets me know when I checked in and when my 8.5 hours will be up.

I used Create-React-App to develop the same.

Now, the API calls work properly in the node server, where I am able to log the data, but when I start a local server using npm start, Chrome is not able to show the data and I get the following error:

Failed to load https://people.zoho.com/people/api/attendance/getAttendanceEntries?authtoken=*******&date=05-Sep-2018&dateFormat=dd-MMM-yyyy&emailId=******&empId=****: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

To get around the problem I had to install Allow-Control-Allow-Origin chrome extension : https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Using this extension, the app works, and I'm able to see the data. But without this extension, I'm not. Have tried including some CORS-related HTTP headers in the js file, but to no effect. Please let me know if more details are required. Thanks!

P.S. I'd also be really grateful if someone could ELI5 why this was happening and how the data transfer from the API server to my client is actually working.


Solution

  • Making a cross-origin request from the browser/client is not allowed by default. That is the CORS restriction enforced by the browsers for security purposes.

    Know about CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    To make this work we have two options,

    • From client call your server-side app using AJAX which will, in turn, call the Zoho API to fetch the details
    • Check if there is an option from API provider to set the "No Access Control Allow Origin" header for their API so that you can hit the API directly from the client

    All other options would be a hack or temporary solution