douxuanling6523 2017-02-24 10: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-28 07: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.

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

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题