【问题标题】:Issue with API PHP reading JSONAPI PHP 读取 JSON 的问题
【发布时间】:2020-08-22 23:04:26
【问题描述】:

处理 JSON 输入的 API 似乎存在问题。 这是我的 API(删除功能)

function doDeleteCustomer() {
global $db;
if(isParamSet(array('id'))) {
    if(isParamAvailable(array('id'))) {
        $customerId = $_REQUEST['id'];
        $sql = "DELETE FROM customers WHERE ID=:customerid";
        $stmt = $db->prepare($sql);
        $stmt->execute(
            array(
                ':customerid' => $customerId
            )
        );
        if($stmt->rowCount() > 0) {
            $response = array();
            $response["error"] = false;
            $response["status"] = 200;
            $response["data"] = array();
            $response["message"] = "Successfully removed customer!";
        } else {
            $response = array();
            $response["error"] = true;
            $response["status"] = 400;
            $response["data"] = array();
            $response["message"] = "Unable to remove customer!";
        }
        return json_encode($response);
    }
}

}

当我在 Postman 中测试时,一切正常,但我已经在 x-www-form-urlencoded 中提供了信息。

但是当我想通过原始 JSON 数据提供输入时,我收到一条消息,指出缺少所需的 id 字段...我做错了什么?

【问题讨论】:

  • 那么是哪个代码在做那个检查。不是您向我们展示的代码
  • @RiggsFolly。我希望我不会说任何愚蠢的话,因为我完全是 API 新手。但是你的意思是client.php吗?

标签: php mysql json api


【解决方案1】:

我找到了,感谢 Zirc 的这个。

我只需要$_REQUEST = json_decode(file_get_contents('php://input'), true); 在第一个 if 语句之前

【讨论】:

    【解决方案2】:

    如果您打算让您的应用程序接受 json,则必须在处理数据之前使用json_decode。或者,如果您希望它同时支持两者,您可以使用try catch 进行切换。

    关于 json_decode 的更多信息可以在herehere 找到。

    【讨论】:

    • 感谢您的回复。因为我是个菜鸟,而且还在学习 API。我需要把 json_decode 放在哪里?
    • 好久没接触PHP了,不过……据我了解,$_REQUEST是接收请求体的变量……所以,如果是接收 JSON 将类似于 $_REQUEST = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 如果您注意到,该变量将等同于一个字符串...因此您需要使用 json_decode 将其转换为对象/字典/哈希图(无论您如何称呼它)为了处理它......所以我相信你需要把json_decode($_REQUEST)放在if语句之前,然后检查id是否存在于请求正文中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多