Cross-Origin Request Blocked: Error In Angular 11 App with PHP Backend Rest API

  angular, php

I create a Angular 10 app with rest api in Php. I host my api on live serve url is as "https://bpegm.co/quiz/leaderboard/create.php" . Whenever I Press Submit button I will get error like this

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://bpegm.co/quiz/leaderboard/create.php. (Reason: CORS preflight response did not succeed).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://bpegm.co/quiz/leaderboard/create.php. (Reason: CORS request did not succeed).

My Angular serivcce.ts code

 saveExamResult(data: any): Observable<any> {
       
        return this.http.post<any>('https://bpegm.co/quiz/leaderboard/create.php', data);
      }

My Component.ts code

onSave() {
    this.saveData = {
      leaderBoard_studentName: this.result.fullName,
      leaderboard_mobile: this.result.mobile,
      leaderboard_district: this.result.dist,
      leaderboard_taluka: this.result.tal,
      leaderBoard_exam_id: this.examId,
      leaderboard_time: this.formatted_min + ':' + this.formatted_sec,
      leaderBoard_marks: this.correctAnswer
    }
    console.log(this.saveData);
    this.service.saveExamResult(this.saveData).subscribe((res) => {
      console.log(res);

    }, error => {
      console.log(error);

    })

  }

My Rest Api Code create.php

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
 
// get database connection
include_once '../config/database.php';
 
// instantiate leaderboard object
include_once '../objects/leaderboard.php';
$database = new Database();
$db = $database->getConnection();
 
$leaderboard = new Leaderboard($db);
 
// get posted data
$data = json_decode(file_get_contents("php://input"));
 
// make sure data is not empty
if(!empty($data->leaderBoard_exam_id)
&&!empty($data->leaderBoard_studentName)
//&&!empty($data->leaderBoard_date)
&&!empty($data->leaderBoard_marks)
&&!empty($data->leaderboard_district)
&&!empty($data->leaderboard_taluka)
&&!empty($data->leaderboard_time)
&&!empty($data->leaderboard_mobile)){
 
    // set leaderboard property values
     
if(!empty($data->leaderBoard_exam_id)) { 
$leaderboard->leaderBoard_exam_id = $data->leaderBoard_exam_id;
} else { 
$leaderboard->leaderBoard_exam_id = '';
}
if(!empty($data->leaderBoard_studentName)) { 
$leaderboard->leaderBoard_studentName = $data->leaderBoard_studentName;
} else { 
$leaderboard->leaderBoard_studentName = '';
}
if(!empty($data->leaderBoard_date)) { 
$leaderboard->leaderBoard_date = $data->leaderBoard_date;
} else { 
$leaderboard->leaderBoard_date = 'current_timestamp()';
}
if(!empty($data->leaderBoard_marks)) { 
$leaderboard->leaderBoard_marks = $data->leaderBoard_marks;
} else { 
$leaderboard->leaderBoard_marks = '';
}
if(!empty($data->leaderboard_district)) { 
$leaderboard->leaderboard_district = $data->leaderboard_district;
} else { 
$leaderboard->leaderboard_district = '';
}
if(!empty($data->leaderboard_taluka)) { 
$leaderboard->leaderboard_taluka = $data->leaderboard_taluka;
} else { 
$leaderboard->leaderboard_taluka = '';
}
if(!empty($data->leaderboard_time)) { 
$leaderboard->leaderboard_time = $data->leaderboard_time;
} else { 
$leaderboard->leaderboard_time = '';
}
if(!empty($data->leaderboard_mobile)) { 
$leaderboard->leaderboard_mobile = $data->leaderboard_mobile;
} else { 
$leaderboard->leaderboard_mobile = '';
}
    $lastInsertedId=$leaderboard->create();
    // create the leaderboard
    if($lastInsertedId!=0){
 
        // set response code - 201 created
        http_response_code(201);
 
        // tell the user
        echo json_encode(array("status" => "success", "code" => 1,"message"=> "Created Successfully","document"=> $lastInsertedId));
    }
 
    // if unable to create the leaderboard, tell the user
    else{
 
        // set response code - 503 service unavailable
        http_response_code(503);
 
        // tell the user
        echo json_encode(array("status" => "error", "code" => 0,"message"=> "Unable to create leaderboard","document"=> ""));
    }
}
 
// tell the user data is incomplete
else{
 
    // set response code - 400 bad request
    http_response_code(400);
 
    // tell the user
    echo json_encode(array("status" => "error", "code" => 0,"message"=> "Unable to create leaderboard. Data is incomplete.","document"=> ""));
}
?>

function create() is as follows

function create(){
     
        // query to insert record
        $query ="INSERT INTO ".$this->table_name." SET leaderBoard_exam_id=:leaderBoard_exam_id,leaderBoard_studentName=:leaderBoard_studentName,leaderBoard_date=:leaderBoard_date,leaderBoard_marks=:leaderBoard_marks,leaderboard_district=:leaderboard_district,leaderboard_taluka=:leaderboard_taluka,leaderboard_time=:leaderboard_time,leaderboard_mobile=:leaderboard_mobile";

        // prepare query
        $stmt = $this->conn->prepare($query);
     
        // sanitize
        
$this->leaderBoard_exam_id=htmlspecialchars(strip_tags($this->leaderBoard_exam_id));
$this->leaderBoard_studentName=htmlspecialchars(strip_tags($this->leaderBoard_studentName));
$this->leaderBoard_date=htmlspecialchars(strip_tags($this->leaderBoard_date));
$this->leaderBoard_marks=htmlspecialchars(strip_tags($this->leaderBoard_marks));
$this->leaderboard_district=htmlspecialchars(strip_tags($this->leaderboard_district));
$this->leaderboard_taluka=htmlspecialchars(strip_tags($this->leaderboard_taluka));
$this->leaderboard_time=htmlspecialchars(strip_tags($this->leaderboard_time));
$this->leaderboard_mobile=htmlspecialchars(strip_tags($this->leaderboard_mobile));
     
        // bind values
        
$stmt->bindParam(":leaderBoard_exam_id", $this->leaderBoard_exam_id);
$stmt->bindParam(":leaderBoard_studentName", $this->leaderBoard_studentName);
$stmt->bindParam(":leaderBoard_date", $this->leaderBoard_date);
$stmt->bindParam(":leaderBoard_marks", $this->leaderBoard_marks);
$stmt->bindParam(":leaderboard_district", $this->leaderboard_district);
$stmt->bindParam(":leaderboard_taluka", $this->leaderboard_taluka);
$stmt->bindParam(":leaderboard_time", $this->leaderboard_time);
$stmt->bindParam(":leaderboard_mobile", $this->leaderboard_mobile);
     
        // execute query
        if($stmt->execute()){
            return  $this->conn->lastInsertId();
        }
     
        return 0;
         
    }

Whernever I check im Mozilla browser RESTED Client extension It works but When I send request from angular App It show error .
Please guide me
Thanks

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.