-1

I built a backend with Spring and now I want to build a frontend with React. When I try to fetch my request URL I get the following error:

Access to fetch at 'http://localhost:8080/demo/getAll' 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.

Here is my code:

const fetchItems = async () => {
fetch('http://localhost:8080/demo/getAll').then(response => response.json()).then(data => 
console.log(data));
};

Does anyone know what the problem is and how do I fix it?

kayakaya
  • 49
  • 3

1 Answers1

1

https://www.w3.org/Security/wiki/Same_Origin_Policy

An origin is defined by the scheme, host, and port of a URL

The port must be the same to past same origin.

For react, you have it proxy, so that you make a request to :3000 and it will act as if you sent it to :8080

If you're using Create React App, this is done pretty easily: https://create-react-app.dev/docs/proxying-api-requests-in-development/

Otherwise, your best bet is probably to modify the CORS headers on your backend: How does Access-Control-Allow-Origin header work?

DemiPixel
  • 1,768
  • 11
  • 19