1

I am trying to fetch the data from an API for which I used fetch method of React.js. But constantly I am seeing this error

Access to fetch at https://api.edamam.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY} from origin http://localhost:3000 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have disable extensions etc but I guess this requires some extra header etc added in request. help please.

j3ff
  • 5,719
  • 8
  • 38
  • 51
  • Hi, could you solve this? I have made a new vue.js app and have the same error in the browser however I don't have it on a postman request. Weird. Any help welcome. Or any other recipe api that does have CORS fixed. Thanks. – Dgloria Aug 16 '22 at 09:01

1 Answers1

2

This issue is not related to React, but to CORS. From the documentation

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

This is a problem that needs to be fixed on the server side. It's not a request in the header that needs to be added, but one in the response. Specifically, you need to add Access-Control-Allow-Origin.

To understand why CORS exists, consider that I make a web site that can make a network request to Gmail on your behalf. That enables me to read your emails. This is prevented by the browser, so that only Gmail can read from Gmail.

There might be other solutions to your problem, depending on which API you are trying to communicate with and what your setup is and what restrictions you have. If you're using create-react-app, a quick fix could be to add this to your package.json:

"proxy": "https://api.edamam.com",

Now remove https://api.edamam.com from your fetch calls. So instead of fetch('https://api.edamam.com/path/to/server'), you need to do fetch('/path/to/server'), Note that you need to restart the development server. You can read more about how this works here

Karamell
  • 1,023
  • 9
  • 23