【问题标题】:Receiving and handling no connect error and 200 OK header接收和处理无连接错误和 200 OK 标头
【发布时间】:2026-01-27 09:05:02
【问题描述】:

我正在使用我自己创建的 API,我正在与之通信,我的代码如下。如果一切正常,API 将返回 json 以及标头“200 OK”。但是,如果连接断开,我会返回“502 Bad Gateway”作为标题。

到目前为止,'CURLOPT_HEADER' 在我的 php 脚本(见下文)中已设置为 false,但现在我已将其设置为 true,以便我可以接收标头并根据标头执行操作。在这里我需要帮助。

我实际上有两件事需要帮助(它们是相互关联的):

    1234563但是,如果我将其设置为 true,实际的标头也会与 ajax 请求一起发回,这会返回错误:“Uncaught SyntaxError: Unexpected token H”(下面 js 代码中的第 10 行)。
  1. 我不知道如何处理错误,如果我的 API 和源之间的连接断开,因此 API 返回“502 Bad Gateway”。我希望 php 脚本通过 ajax 请求将该信息发送回,以便可以在 js 文件中进行处理。

所以,请帮帮我。提前致谢!

PHP:

$url = 'http://theurl.com';

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);

$response = curl_exec($ch);

if(!$response) {
    // <--- ??
}

curl_close($ch);

echo json_encode($response);

JS:

1.    $.ajax({
2.        url:'./php/apihandling.php',
3.        type:'post',
4.        dataType:'json',
5.            data:{ 
6.            data: data
7.       },
8.       success: function(data) {
9.           var content = JSON.parse(data);
10.          console.log(content);
11.       },
12.      error: function (xhr, ajaxOptions, thrownError) {
13.          console.log(xhr.status);
14.          console.log(thrownError);
15.      }
16.  });

【问题讨论】:

    标签: php ajax json api error-handling


    【解决方案1】:

    您可以使用 curl_errno 检查您的 API 如何响应您的请求,您也可以尝试使用 API“状态标志”来避免 JQuery 中的错误

    ...
    // Check if any error occurred
    if(!curl_errno($ch))
    {
     $info = curl_getinfo($ch);
    
     //close the connection
     curl_close($ch);
     $result["API_status"]=0;
     $result["error"]=$info;
     //kill the script and echo the json
     die(json_encode($result));
    } 
    else
    {
    $result["API_status"]=1;
    curl_close($ch);
    $result["response"]=$response;
    echo json_encode($result);
    }
    

    现在让我们试试你的 jquery 脚本

    $.ajax({
        url: './php/apihandling.php',
        type: 'post',
        dataType: 'json',
        data: {
            data: data
        },
        success: function(data) {
            //no need for this, datatype is json already   
            //var content = JSON.parse(data);
            if (data["API_status"]) {
                alert("wow API is up and healthy");
                //do some stuff with the json
                $.each(data["response"], function(index, value) {
                    //loop this
                });
            } else {
                alert("Oh, no. RIP API");
                console.log(data["error"]);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    });
    

    【讨论】:

    • 非常感谢您的回答。但是,当我尝试它时,它无法正常工作。即使从 API 成功检索数据,$result["API_status"] 也设置为 0。当我 console.log 退出 js 脚本中的数据时,它包含正确的数据,即使 API_status 设置为 0。我在这里复制/粘贴了我的代码:jsfiddle.net/Rmwyt ...如果您想看看...看看我是否做错了什么。再次感谢!