php - Slim - 如何发送带有 "Content-Type: application/json" header 的响应?

标签 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 对象是不可变的并且 因此,如果您想在之后退回它,则必须退回或重新分配 同时。

最佳答案

所以,而不是这个:

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

一切都很好。

关于php - Slim - 如何发送带有 "Content-Type: application/json" header 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34646008/

相关文章:

php - NGINX使用Slim API框架从子目录重定向到根

php - 消息 : SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

php - 帮助 MySQL 查询使用 LIKE AND OR 语句组合 2 个表?

php - 我无法在行中显示我的数据库元素

php - SlimPHP - 扩展 Twig (函数)的奇怪错误

php - 如何配置 Twig 来查找模板?

javascript - 向 Google Calendar API 发出服务器到服务器的请求

php - 发送无表单的 POST 数据

PHP异常: SQLSTATE[42000]: Syntax error or access violation: 1064

php - mysql 更新或插入多条记录(如果表中尚不存在)