我有这个简单的 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
?我做错了什么?
EDIT:
好吧,经过两个小时的头撞墙后,我偶然发现了这个答案:
https://github.com/slimphp/Slim/issues/1535 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');}
一切都很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)