我有一个简单的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对象是不可变的,因此,如果您想在时间之后返回它,就必须返回或重新分配它。
发布于 2016-01-07 02:08:22
所以,代替这个:
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');}一切都很好。
发布于 2016-06-17 15:37:44
对于V3,withJson()是可用的。
所以你可以做这样的事情:
return $response->withStatus(200)
->withJson(array($request->getAttribute("route")
->getArgument("someParameter")));注意:确保返回$response,因为如果您忘记了,响应仍然会出现,但不会是application/json。
发布于 2018-12-01 21:48:52
对于V3,根据苗条博士最简单的方法是:
$data = array('name' => 'Rob', 'age' => 40);
return $response->withJson($data, 201);这将自动将Content设置为application/json;charset=utf-8,并允许您也设置HTTP代码(如果省略,默认为200 )。
https://stackoverflow.com/questions/34646008
复制相似问题