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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测