超薄-如何使用"Content-Type:Application/json&Quot;标头发送响应? [英] Slim - How to send response with "Content-Type: application/json" header?

查看:12
本文介绍了超薄-如何使用"Content-Type:Application/json&Quot;标头发送响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的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 SlimApp();

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

推荐答案

so,而不是这个:

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

一切都很好。

这篇关于超薄-如何使用&quot;Content-Type:Application/json&Quot;标头发送响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆