You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用fetch API获取数据库信息时遇net::ERR_CONNECTION_REFUSED错误求助

使用Fetch API获取数据库信息时遇到连接拒绝错误

出现以下错误:

  • net::ERR_CONNECTION_REFUSED
  • TypeError: Failed to fetch
  • 报错位置:at HTMLDocument.requestItems (script.js:56:5)

相关代码

db.php(数据库连接代码)

$conn=new mysqli("localhost:3306", "root", "", "online_canteen_system");
if($conn->connect_errno){
    echo json_encode(['error'=>$conn->connect_error]);
    exit();
}

items.php(数据查询代码)

<?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();
}

script.js(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));
}

排查与修复步骤

  • 确认Web服务端口:检查你的Web服务(Apache/Nginx)是否运行在8080端口。如果服务用的是默认80端口,把Fetch请求的URL改成http://localhost/backend/items.php。
  • 修正PHP变量名:items.php中使用了未定义的$_conn,而db.php里定义的连接变量是$conn,将$_conn->query($stmt)改为$conn->query($stmt)。
  • 验证数据库连接:直接访问db.php的URL,确认返回的JSON没有连接错误。
  • 检查文件路径:确保backend/items.php在Web服务的根目录下,路径拼写无错误。
  • 测试PHP接口:在浏览器中直接访问items.php的URL,确认能返回合法的JSON数据,而非PHP报错信息。

内容的提问来源于stack exchange,提问作者Hena Garter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:20:59