如何 return 使用自定义状态代码和消息作为 JSON 响应主体响应 Slim Framework
How to return Response with custom status code and message as JSON for response body with Slim Framework
我是 Slim 框架的新手。我想知道如何 return 根据需要使用正文和状态代码进行响应。目前,它仅在查询 returns 记录时按我的意愿执行,但如果查询失败(例如 select * 来自 notexiststable)或 returns 什么都没有,我看到了 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;
});
提前致谢!
状态代码 204
是 No 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 将发送给客户端。
我是 Slim 框架的新手。我想知道如何 return 根据需要使用正文和状态代码进行响应。目前,它仅在查询 returns 记录时按我的意愿执行,但如果查询失败(例如 select * 来自 notexiststable)或 returns 什么都没有,我看到了 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;
});
提前致谢!
状态代码 204
是 No 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 将发送给客户端。