php Slim - 如何使用“Content-Type: application/json”标头发送响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34646008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Slim - How to send response with "Content-Type: application/json" header?
提问by branquito
I have this simple REST api, done in 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();
however, I can't get browser to send me application/json
content type, it
always sends text/html
? What I am doing wrong?
但是,我无法让浏览器向我发送application/json
内容类型,它总是发送text/html
? 我做错了什么?
EDIT:
编辑:
Ok, after two hours of hitting the head against the wall, I stumbled upon this answer:
好吧,在用头撞墙两个小时后,我偶然发现了这个答案:
https://github.com/slimphp/Slim/issues/1535(at the bottom of a page)
which explains what happens, appears that response
object is immutable and
as such it must be returned or reassigned if you want to return it after
while.
https://github.com/slimphp/Slim/issues/1535(在页面底部)解释了发生的情况,似乎该response
对象是不可变的,因此如果您想在一段时间后返回它,则必须返回或重新分配它.
回答by branquito
So, instead of this:
所以,而不是这个:
if($student) {
$response->withHeader('Content-Type', 'application/json');
$response->write(json_encode($student));
return $response;
} else { throw new PDOException('No records found');}
Do like this:
这样做:
if($student) {
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($student));
} else { throw new PDOException('No records found');}
And all is well and good.
一切都很好。
回答by conrad10781
For V3, withJson()
is available.
对于 V3,withJson()
可用。
So you can do something like:
因此,您可以执行以下操作:
return $response->withStatus(200)
->withJson(array($request->getAttribute("route")
->getArgument("someParameter")));
Note:Make sure you return the $response
because if you forget, the response will still come out but it will not be application/json
.
注意:确保您返回 ,$response
因为如果您忘记了,响应仍然会出现,但不会是application/json
。
回答by benyafai
For V3, the simplest method as per the Slim docsis:
对于 V3,根据Slim 文档,最简单的方法是:
$data = array('name' => 'Rob', 'age' => 40);
return $response->withJson($data, 201);
This automatically sets the Content-Type to application/json;charset=utf-8
and lets you set a HTTP status code too (defaults to 200 if omitted).
这会自动将 Content-Typeapplication/json;charset=utf-8
设置为并让您也设置 HTTP 状态代码(如果省略,则默认为 200)。
回答by jcubic
You can also use:
您还可以使用:
$response = $response->withHeader('Content-Type', 'application/json');
$response->write(json_encode($student));
return $response;
because withHeader
return new response object. That way you have more then one write and code between.
因为withHeader
返回新的响应对象。这样一来,您就可以进行多次编写和编写代码。