Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS API Data Fetching CORS error

Tags:

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"}]}

like image 555
Last Avatar asked Jul 02 '18 01:07

Last


People also ask

How do I fix a CORS error in API?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.

What is CORS in react JS?

What Is CORS? CORS is a technique that allows you to make an ajax request to a server of a different domain. This is very useful if you want to consume an API directly on your client — something that is absolutely needed if you're writing a Jamstack web app.

How do you fix CORS origin error?

To get rid of a CORS error, you can download a browser extension like CORS Unblock ↗. The extension appends Access-Control-Allow-Origin: * to every HTTP response when it is enabled. It can also add custom Access-Control-Allow-Origin and Access-Control-Allow-Methods headers to the responses.


2 Answers

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.

like image 108
Dat Pham Avatar answered Sep 26 '22 08:09

Dat Pham


This is what I did using vite

Package.json file add: "proxy": "http://api_website_where_the_request_is_comming/",

App component or whatever component you making the call do this

let endpoint = /api/your_endpoint/;

fetch(endpoint).then(function (response) {
    return response.json()
}) 
.then(function (jsonData){
    console.log('Banner log', jsonData);
})
like image 1
Pinto Manuel Avatar answered Sep 27 '22 08:09

Pinto Manuel