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