Getting response in localhost but getting CORS error on infinityfree hosting server

Error Message

Access to XMLHttpRequest at ‘http://niceday.free.nf/api.php’ 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.

Other Information

These are my entire code:
header(“Content-Type: application/json”);
header(“Access-Control-Allow-Origin: *”);
header(“Access-Control-Allow-Methods: POST, OPTIONS”);
header(“Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Methods”);

try {

if($_SERVER["REQUEST_METHOD"] == "POST" ){
    $data = json_decode(file_get_contents("php://input"), true);
    include '../config/db.php';
    
    $username = $data["username"];
    
    $query = $conn->prepare("SELECT * FROM `user` WHERE `username` = ?");
    $query->bindParam(1, $username, PDO::PARAM_STR);
    if($query->execute()){
        $user = $query->fetch(PDO::FETCH_ASSOC);
        if($user){
            echo json_encode(array("user_id" => $user["id"],"message" => "Logged in Successfully", "status" => true));   
        }else{
            echo json_encode(array("message" => "Wrong Username", "status" => false));    
        }
    }else{
        echo json_encode(array("message" => "Wrong Username", "status" => false));    
    }  
}

} catch (exception $e) {
echo json_encode(array(“message” => “Something Went Wrong!”, “status” => false));
}

?>

Hi and welcome to the forum!

3 Likes

To give a little bit of context to @JxstErg1’s post: our hosting does not support or allow CORS. We provide hosting for websites, not API’s.

If you are building a frontend Javascript application with a PHP backend, you can host it on our hosting, as long as you’re hosting them on the same hostname. And for development, you should run both the Javascript application and the PHP backend locally.

6 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.