skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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:

    • Verify CORS support: Check if the API server explicitly allows
      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.
    • Configure the server for CORS: If the API server does not support
      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.
    • Consider request credentials: If your API requires authentication and
      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.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search