当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《Slim-如何使用"Content-Type:application/json"标题发送响应?》经验,为你挑选了2个好方法。

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

 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对象是不可变的,因此如果你想在之后返回它必须返回或重新分配.



1> branquito..:

所以,而不是这个:

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');}

一切都很好.



2> conrad10781..:

对于V3,withJson()可用.

所以你可以这样做:

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

注意:确保你返回,$response因为如果你忘了,响应仍然会出现,但不会application/json.

推荐阅读
k78283381
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有