![](/img/trans.png)
[英]The usage of `header(“Content-type:application/json”);`
[英]Slim - How to send response with “Content-Type: application/json” header?
我有這個簡單的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');}
一切都很好。
對於V3, withJson()
可用。
所以你可以這樣做:
return $response->withStatus(200)
->withJson(array($request->getAttribute("route")
->getArgument("someParameter")));
注意:確保返回$response
因為如果您忘記了,響應仍然會出現,但它不會是application/json
。
對於V3,根據Slim文檔最簡單的方法是:
$data = array('name' => 'Rob', 'age' => 40);
return $response->withJson($data, 201);
這會自動將Content-Type設置為application/json;charset=utf-8
並允許您設置HTTP狀態代碼(如果省略,則默認為200)。
您還可以使用:
$response = $response->withHeader('Content-Type', 'application/json');
$response->write(json_encode($student));
return $response;
因為withHeader
返回新的響應對象。 這樣你就可以有多個寫入和代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.