I have a React client application and I need to make API requests via this app using axios
. I get the below error. The same API works via curl
and Postman and in browser tab.
How do I make this work through my client app?
Error –
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some-app.com. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some-app.com. (Reason: CORS request did not succeed). Status code: (null).
2
Answers
CORS has to be enabled on the server where the API is running on. You cannot enable this in your client code. If the API supports CORS the browser will do the request
The error you’re experiencing is related to the Same Origin Policy implemented by web browsers. This policy is a security measure that restricts API requests from a different origin (such as a different domain, protocol, or port) than the one serving your React client application. The error message specifically mentions that the CORS header ‘Access-Control-Allow-Origin’ is missing, which is required for the browser to allow the request.
To resolve this issue, you’ll need to enable Cross-Origin Resource Sharing (CORS) on the server hosting the API you’re trying to access. CORS is a mechanism that allows a server to specify which origins are permitted to access its resources.
Here are steps you can take to enable CORS and make the API requests work:
requests from your React client’s domain. Look for the presence of
the ‘Access-Control-Allow-Origin’ header in the server’s response. If
the header is missing or set to a specific domain, you’ll need to
configure the server to allow requests from your domain.
CORS or restricts access to specific domains, you’ll need to
configure it to allow requests from your React client’s domain. This
typically involves setting the ‘Access-Control-Allow-Origin’ header
to the appropriate value on the server-side. You may need to refer to
the API server’s documentation or consult with its administrator for
guidance on how to configure CORS correctly.
uses cookies for session management, you might also need to include
the ‘withCredentials’ option in your Axios request configuration.
This ensures that cookies and authentication headers are sent along
with the request, allowing the server to recognize and authenticate
the client properly.