如何使用自定义状态代码返回响应,并使用Slim Framework

时间:2017-02-24 10:16:10

标签: php json slim

我是Slim框架的新手。我想知道如何使用正文和状态代码返回响应。现在,如果查询返回记录,它只会按照我的意愿执行,但如果查询失败则不会(例如select * from notexiststable)或者不返回任何内容,并且在Firefox中我看到两种情况下状态都是204。

所以这里是代码:

$app->get('/models', function (Request $request, Response $response) {
    $conn = getConnection();
    $result = pg_query($conn, "SELECT * FROM model where m_id = 2;");  //this will return 0 record!

    if  (!$result) {
        $data = array("Error Message" => 'Query did not execute successfully');
        $newResponse = $response->withJson($data, 500);
    }
    else {
        if (pg_num_rows($result) == 0) {
            $data = array("Warning Message" => "There's no existent Model!");
            $newResponse = $response->withJson($data, 204);

        }
        else {
            $data = array();
            while ($row = pg_fetch_assoc($result)) {
                $data['Models'][] = $row;               
            }
            $newResponse = $response->withJson($data, 200);
        }
    }

    return $newResponse;

});

先谢谢你了!

1 个答案:

答案 0 :(得分:0)

状态代码204No Content,HTTP规范指出消息中不能有正文。

将错误的状态代码更改为错误代码,例如400

即。变化:

if (pg_num_rows($result) == 0) {
    $data = array("Warning Message" => "There's no existent Model!");
    $newResponse = $response->withJson($data, 204);
}

为:

if (pg_num_rows($result) == 0) {
    $data = array("Warning Message" => "There's no existent Model!");
    $newResponse = $response->withJson($data, 400);
}

并将JSON发送给客户端。