Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS error using fetch API - React create app

I'm consuming an API using fetch but i'm getting CORS error. I tried multiples headers, but I'm not understading what's the problem.

I'm not the owner of the API, so I couldn't change it, but checking the response it's returning access-control-allow-origin.

Following is my request method:

export const execPOST = (url, body) => {
  return fetch(url, {
    method: "POST",
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(body)
  });
};

The response is:

Request URL: http://api
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: ip
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Access-Control-Allow-Origin: *

Isn't this response above enough to allow my request?

console error:

OPTIONS http://api net::ERR_ABORTED 405 (Method Not Allowed) Access to fetch at 'http://api' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I got this working (meanwhile I develop) using "https://cors-anywhere.herokuapp.com/", but I don't think that I should use this for production enviroment.

I found a lot of material about this problem, but nothing that worked besides implements a backend to make the request or use something else as a proxy to make the request and so on...

like image 427
Victor Bello Avatar asked Mar 05 '23 00:03

Victor Bello


2 Answers

Update code as given below (use 'mode' with the value 'no-cors' ):

For more details follow the link => https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

export const execPOST = (url: string, body: any) => {
  return fetch(url, {
    mode: 'no-cors',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  });
};
like image 191
Vibhas Avatar answered Mar 11 '23 19:03

Vibhas


CORS headers are set by the API to protect users from malicious code making requests to sites on their behalf.

This means that you cannot enable or disable it from the client side as the Access-Control-Allow-Origin header is a server side only header.

If you don't have access to the API to change the headers then you won't be able to use the API from the client side.

In production you would have to create your own API that will handle the requests to the API you are trying to contact.

like image 45
braza Avatar answered Mar 11 '23 19:03

braza