'Fetch Post CORS error PHP-REACT: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

I am trying to create a request to my backend local PHP server using React like the following.

const requestOptions = {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(productData),
};

fetch(process.env.REACT_APP_BASE_URL + '/add-product', requestOptions)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

The error I get after I make a call to the server is: Access to fetch at 'http://localhost:8000/add-product' 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

In my backend entry point (index.php) I have the following:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');

But I still get the error.

I also tried to add some more headers from some other answers

header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

Nothing seems to be working fine. Can anyone please figure out what the problem is?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source