如何使用Slim Framework将响应自定义状态代码和消息作为JSON返回给响应主体

如何使用Slim Framework将响应自定义状态代码和消息作为JSON返回给响应主体

问题描述:

I'm new with Slim framework. I want to know how to return response with the body and status code as I wish. For now, it only performs as I wish if the query returns records, but not if the query failed (e.g. select * from notexiststable) or returns nothing and with Firefox I see the status is 204 in both cases.

So here's the code:

$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;

});

Thank you in advanced!

Status code 204 is No Content and the HTTP specification notes that there cannot be a body in the message.

Change the status code for your error to an error code, such as 400.

ie. Change:

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

to:

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

and the JSON will be sent to the client.