Slim - 如何使用" Content-Type:application / json"发送响应头?

时间:2016-01-07 01:40:12

标签: php slim

我有这个简单的REST api,在Slim中完成,

<?php

require '../vendor/autoload.php';

function getDB()
{
    $dsn = 'sqlite:/home/branchito/personal-projects/slim3-REST/database.sqlite3';

    $options = array(
        PDO::ATTR_PERSISTENT => true,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    );
    try {

        $dbh = new PDO($dsn);

        foreach ($options as $k => $v)
            $dbh->setAttribute($k, $v);

        return $dbh;
    }
    catch (PDOException $e) {
        $error = $e->getMessage();
    }
}

$app = new \Slim\App();

$app->get('/', function($request, $response) {
    $response->write('Bienvenidos a Slim 3 API');
    return $response;
});

$app->get('/getScore/{id:\d+}', function($request, $response, $args) {

    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT * FROM students
            WHERE student_id = :id
            ");

        $stmt->bindParam(':id', $args['id'], PDO::PARAM_INT);
        $stmt->execute();

        $student = $stmt->fetch(PDO::FETCH_OBJ);

        if($student) {
            $response->withHeader('Content-Type', 'application/json');
            $response->write(json_encode($student));

        } else { throw new PDOException('No records found');}

    } catch (PDOException $e) {

        $response->withStatus(404);
        $err =  '{"error": {"text": "'.$e->getMessage().'"}}';
        $response->write($err);
    }
    return $response;
});

$app->run();

但是,我无法让浏览器向我发送application/json内容类型 总是发送text/html?我做错了什么?

修改

好的,经过两个小时的撞击墙头后,我偶然发现了这个答案:

https://github.com/slimphp/Slim/issues/1535(在页面底部) 这解释了会发生什么,看来response对象是不可变的 因此,如果您想在之后退货,则必须退回或重新分配 而

4 个答案:

答案 0 :(得分:30)

所以,而不是:

if($student) {
            $response->withHeader('Content-Type', 'application/json');
            $response->write(json_encode($student));
            return $response;

        } else { throw new PDOException('No records found');}

这样做:

if($student) {
    return $response->withStatus(200)
        ->withHeader('Content-Type', 'application/json')
        ->write(json_encode($student));

} else { throw new PDOException('No records found');}

一切都很好。

答案 1 :(得分:13)

对于V3,withJson()可用。

所以你可以这样做:

return $response->withStatus(200)
                ->withJson(array($request->getAttribute("route")
                ->getArgument("someParameter")));

注意:确保您返回$response,因为如果您忘记了,响应仍会显示但不会是application/json

答案 2 :(得分:2)

对于V3,根据Slim docs,最简单的方法是:

$data = array('name' => 'Rob', 'age' => 40);
return $response->withJson($data, 201);

这会自动将Content-Type设置为application/json;charset=utf-8,并让您也设置HTTP状态代码(如果省略,则默认为200)。

答案 3 :(得分:0)

您还可以使用:

$response = $response->withHeader('Content-Type', 'application/json');
$response->write(json_encode($student));
return $response;

因为withHeader返回新的响应对象。这样一来,您之间可以进行多次写入和编码。