-3

need help for ReactJs. I still learning reactJs to fetch data from PHP backend. I'm using Xampp as my local server. but when i integrate fetch function on ReactJs, i got CORS policy error.

here is my code from on my App.jsx

useEffect(() => { 
    fetch("http://localhost:81/opencart/index.php?route=api/create", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items: [{ id: "xl-tshirt" }] }),
      })
      .then((res) => res.json())
      .then((data) => setClientSecret(data.clientSecret));
  }, []);

On my reactJs package.json file i added this

"proxy": "http://localhost:81/"

but still display error on browser console

Access to fetch at 'http://localhost:81/opencart/index.php?route=api/create' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

How do I resolve this?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
ferdinand
  • 325
  • 2
  • 14
  • Does this answer your question? [No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API](https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe) – Heretic Monkey Jun 02 '22 at 23:36
  • Looks like @HereticMonkey spoke for me! – manjiro sano Jun 02 '22 at 23:45

1 Answers1

-1

CORS issue is definitely coming from Server. So the ideal way is to set your server to accept your request from cross origin.

Seems you are working with server built with PHP, then check your backend server to add CORS configuration.

For Express.js and others are having several way to add it such as adding 'cors` middleware.

Satel
  • 169
  • 1
  • 9