-1

I'm able to use Postman to fetch this API from Fruityvice. But when I run it locally, I run into CORS issues.

I've been referencing Attempted Solution and Attemped Solution 2 to try and clear the error, but no luck.

Any pointers and where I'm going wrong? Thank you!

Initial Fetch Call

const fetchFruitInformation = async() => {

  const response = await fetch("https://www.fruityvice.com/api/fruit/all");
  if (!response.ok) {
    throw new Error(response.statusText);
  }

  return response.json();
};
Which gives me a CORS error

Error

Access to fetch at 'https://www.fruityvice.com/api/fruit/all' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So then I add {mode: 'no-cors'} and also {mode: 'cors}

Updated Fetch Call

const fetchFruitInformation = async() => {

  const response = await fetch("https://www.fruityvice.com/api/fruit/all", {
    mode: 'no-cors'
  });

  if (!response.ok) {
    throw new Error(response.statusText);
  }

  return response.json();
};

Which throws an error

apiCalls.js:7 Uncaught (in promise) Error at fetchFruitInformation (apiCalls.js:7)

mfaccord
  • 225
  • 1
  • 3
  • 14
  • https://www.telerik.com/blogs/dealing-with-cors-in-create-react-app – srWebDev Sep 04 '21 at 15:06
  • Why `no-cors`? It says "if an opaque response serves your needs" - I don't think it does, because you attempt to actually read the response the server returned... – CherryDT Sep 04 '21 at 15:13

1 Answers1

0

https://www.fruityvice.com/api/ doesn't send Access-Control-Allow-Origin: * header in the response of the request, thus browser will complain CORS issue while Postman won't. One solution is to proxy all your related requests to https://www.fruityvice.com/api in the backend.

Iceberg
  • 2,744
  • 19
  • 19