宁静的api不返回数据

时间:2018-08-30 14:45:22

标签: php api slim

我正在使用一个苗条的框架构建一个api,但是它没有返回数据,但是我的状态为200。

$app->run();

$app->post('/blog', 'AddBlogPost'); 

function AddBlogPost()
  {
    $request = \Slim\Slim::getInstance()->request();
    $data = json_decode($request->getBody());
    $id = $data->id;
    $title = $data->title;
    $content = $data->content;
    $date = $data->date;
    $category = $data->category;

    $query = "INSERT INTO blog ('id','title','content','date','category') 
    VALUES (:id,:title,:content,:date,:category)"; 

    try{
        $db = getDB();
        $stmt = $db->prepare($query);
        $stmt->bindParam("title", $title, PDO::PARAM_STR);
        $stmt->bindParam("content", $content, PDO::PARAM_STR);
        $stmt->bindParam("date", $date, PDO::PARAM_STR);
        $stmt->bindParam("category", $category, PDO::PARAM_STR);
        $stmt->execute();
        $db = null;

        echo '{"success":{"status":"post added"}}';

    }catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
  }
  }

1 个答案:

答案 0 :(得分:1)

对于Slim框架,您不应使用echo,而应返回PSR-7响应。 Slim将响应对象作为第二个参数传递到回调中。它还提供了一些帮助来创建JSON。

function AddBlogPost(Request $request, Response $response) {
    ...
    try {
        ...

        return $response->withJson(['success' => ['status' => 'post added']]);

    }
    catch (PDOException $e) {
        return $response->withJson(['error' => ['text' => $e->getMessage()]]);
    }
}