ReactJS API Data Fetching CORS error

102,298

The CORS settings need to be setup in the API to allow access from your React app domain. No CORS settings, no AJAX from different domains. It's simple as that. You can either add CORS settings to your company API (this is unlikely to happen) or you can work around like described below:

The CORS is solely a mechanism of client browser to protect users from malicious AJAX. So one way to work around this is proxying your AJAX request from your React app to its own web server. As Vincent suggests, the create-react-app provides an easy way to do this: in your package.json file, simply chuck "proxy": "http://your-company-api-domain". For more details, please see this link

Then in your react app you can using relative URL like this: fetch('/api/endpoints'). Notice that the relative URL has to match with your company API. This will send a request to your server, then the server will forward the request to your company API and return the response back to your app. Since the request is handled in the server-to-server way not browser-to-server so the CORS check won't happen. Therefore, you can get rid of all unnecessary CORS headers in your request.

Share:
102,298
Last
Author by

Last

Huzzah

Updated on April 23, 2020

Comments

  • Last
    Last about 4 years

    I've been trying to create a react web app for a few days now for my internship and I've encountered a CORS error. I am using the latest version of reactJS, and placing this in the create-react-app, and below is the code for fetching:

    componentDidMount() {
      fetch('--------------------------------------------',{
        method: "GET",
        headers: {
          "access-control-allow-origin" : "*",
          "Content-type": "application/json; charset=UTF-8"
        }})
      .then(results => results.json())
      .then(info => {
        const results = info.data.map(x => {
          return {
            id: x.id,
            slug: x.slug,
            name: x.name,
            address_1: x.address_1,
            address_2: x.address_2,
            city: x.city,
            state: x.state,
            postal_code: x.postal_code,
            country_code: x.country_code,
            phone_number: x.phone_number,
          }
        })
        this.setState({warehouses: results, lastPage: info.last_page});
      })
      .then(console.log(this.state.warehouses))
     }
    

    I'm sorry that I can't post the url for the API due to company rules, however, it is confirmed that there are no CORS setting in the API backend.

    However, I encounter the following errors when run on mozilla

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ------------------. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
    

    and

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ---------------------------------------------. (Reason: CORS request did not succeed).
    

    If run on chrome it gives the following error

    Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
    

    and

    Failed to load --------------------------------------------------------: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
    

    and

    Uncaught (in promise) TypeError: Failed to fetch
    

    Another thing is that I am able to open the url in my browsers with no problems or whatsoever.

    Please help and thanks!

    Additional Information

    The reason I added the CORS setting is because it gives a CORS error, so removing it does not really solve the issue.

    Next I tried to perform proxy setting, however, it now gives

    Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
    

    According to the internet this is caused becasue the response is not a JSON. However when I checked the API it gives this

    api img

    which means that return type should be a JSON right?

    Additional Info

    checking the respond will yield this

    {"status":200,"total":1,"per_page":3,"current_page":1,"last_page":1,"next_page_url":null,"prev_page_url":null,"from":1,"to":3,"data":[{"id":1,"slug":"america","name":"america","address_1":"USA Court","address_2":"USA","city":"USA","state":"USA","postal_code":"94545","country_code":"US","phone_number":"10000001","created_by":null,"updated_by":null,"created_at":"2017-11-10 11:30:50+00","updated_at":"2018-06-28 07:27:55+00"}]}

  • Last
    Last almost 6 years
    Hello, I added the proxy settings and the CORS error did disappear, but a new error appeared 'Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0'
  • Dat Pham
    Dat Pham almost 6 years
    @Last that means you bypass the CORS. But the response is not a valid JSON. Notice that the response has "<" as the first character so it's likely in XML format. Could you inspect your response and post it in your questtion?
  • Prajwal
    Prajwal almost 6 years
    Sorry to interrupt, but it is probably the proxy server responding with 404.
  • Last
    Last almost 6 years
    what happens if the proxy server responds with 404?
  • Last
    Last almost 6 years
    posted the response
  • Dat Pham
    Dat Pham almost 6 years
    @Last the response you post is actually the wrapper object of the returned data. It's only tell that the request was handled successfully. Could you get and post the content of the response instead? Details here: developer.mozilla.org/en-US/docs/Web/API/Body/text
  • Last
    Last almost 6 years
    @DatPham sorry i didn't know that still new to react. Updated it
  • Dat Pham
    Dat Pham almost 6 years
    @Last the response you got was a valid JSON and seem like you got the data from the API. So I don't know what error you got here. Perhaps you can add a .catch(error => console.log(error)) to your fetch call and debug from there
  • Last
    Last almost 6 years
    @DatPham thanks to you I was able to find the error. After knowing how to look at the response, I knew that there was nothing wrong with the API, so I decided to just remove the mapping and that fixed the problem. I also tried various things and found that CORS error appears when you make a mistake in pulling information that does not exist