I wrote an API that has manages a database, and that on get requests it has to send a JSON file with the data from the database. Also, from the frontend I want to call this API using fetch(), but I get a null response. What should I do?
The api code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include_once '../Model/database.php';
include_once '../Model/verifiedEvents.php';
$db = new database();
$event = new verifiedEvents();
$result = $event->read();
$count = $result->num_rows;
if ($count > 0){
$outputArray = array();
while($row = $result->fetch_assoc()){
array_push($outputArray, $row);
}
echo json_encode($outputArray);
} else {
echo json_encode(
array('message' => 'No events found')
);
}
?>
The clientside Javascript code:
const events_api_url = 'http://localhost/Proiect/API/getVerifiedEvents.php';
const user_locations_api_url = 'http://localhost/Proiect/API/getUserLocations.php';
async function getEvents(){
const response = await fetch(events_api_url, {method: 'GET', mode: 'cors', cache: 'default', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'}});
console.log(response);
const data = await response.json;
console.log(data);
const {description, title, longitude, latitude} = data;
console.log(description);
console.log(title);
console.log(longitude);
console.log(latitude);
console.log(" ");
}
getEvents();