skip to Main Content

I’m getting CORS error while making REST API calls from React JS application.
Also, when I tried the API call directly from the browser, I’m able to get the data.

I need a solution to fix this CORS error in production environment. I don’t want to use proxy in prod env.

I tried all the headers but nothing helps.

2

Answers


  1. You should define a CORS configuration inside your REST API to authorize all request from you react app. Indeed, CORS error comes when you try to communicate with an foreign origin (different domain, port).

    Read this article :

    https://developer.mozilla.org/fr/docs/Web/HTTP/CORS

    Login or Signup to reply.
  2. It seems you have to set the response header "Access-Control-Allow-Origin" with your client’s (React App) URL inside your API.

    For example:

    Access-Control-Allow-Origin: https://myreactapp.com/
    

    You also can set the header’s value to "*", but it’s not secure, because any website will able to call your API this way.

    If you host your API via IIS, you can set this header in Web.Config

    <httpProtocol>
       <customHeaders>
          <add name="Access-Control-Allow-Origin" value="https://myreactapp.com/" />
       </customHeaders>
    </httpProtocol>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search