React app is giving me CORS policy error. How can I fix it?

Problem:

I’m trying to make a login page in React using Vite. To verify login credentials I have created an API in PHP. When I test the API with Postman it returns a data but with my react application it is not working.

Can you kindly help me to fix it? My react app is currently on localhost and my API is on my website. I have added the link to the API below.

Errors in console:

Access to XMLHttpRequest at ‘http://ahmadchattha.com/projects/taleemei/API/index.php’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

http://ahmadchattha.com/projects/taleemei/API/index.php net::ERR_FAILED 301 (Moved Permanently)

PHP Code:

try {
    $con = new PDO("mysql:host=$host;dbname=$database", $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['email']) && !empty($_POST['password'])) {
        $userEmail = $_POST['email'];
        $userPassword = $_POST['password'];
        try {

App.jsx:

import $ from 'jquery';
$.ajax({
  type: 'POST',
  url: form.attr('action'),
  dataType: "json",
  data: form.serialize(),
  crossDomain: true,
  format: "json",
  success(data) {
    setResult(data);
    console.log(data)
  },
});

Before using jQuery I also tried to use Axios but had no success with that. Also don’t have very much idea of what I should use because I’m totally new to React.

Thanks for any help 🙂

enter image description here