douxuanling6523 2017-02-24 02:16
浏览 46
已采纳

如何使用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!

展开全部

  • 写回答

1条回答 默认 最新

  • dongwo5589 2017-02-27 23:56
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部