I’m trying to use fetch API to get information about my database but I keep getting “net::ERR_CONNECTION_REFUSED
TypeError: Failed to fetch
at HTMLDocument.requestItems (script.js:56:5)” error
Here’s my db.php code to connect to database
$conn=new mysqli("localhost:3306", "root", "", "online_canteen_system");
if($conn->connect_errno){
echo json_encode(['error'=>$conn->connect_error]);
exit();
}
and here’s my items.php code
<?php
require 'db.php';
header('Access-Control-Allow-Origin: *');
if($_SERVER['REQUEST_METHOD']==="GET"){
$stmt = "select name from items where status=1;";
if($result= $_conn->query($stmt)){
$arr= array();
while($name= $result->fetch_assoc()['name']){
array_push($arr,$name);
}
echo json_encode(['items'=>$arr]);
}
else{
echo json_encode(['error'=>'an error occured']);
}
exit();
}
here is the js code for the fetch api
document.addEventListener('DOMContentLoaded', requestItems);
function requestItems() {
fetch("http://localhost:8080/backend/items.php")
.then((res) => res.json())
.then((data) => {
console.log(data);
}
)
.catch(err => console.log(err));
}