【发布时间】:2018-11-15 20:51:03
【问题描述】:
我想在symfony 中使用guzzlehttp 使用rest api 进行post call ...
我写了这段代码,但是响应
/**
* @Route("/post/")
*/
public function postAction()
{
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $url, [
'form_params' => [
'username' => 'test',
'password' => 'test',
]
]);
return $this->render('esterne/post.html.twig', array(
'response'=>$response,
));
}
这是树枝文件post.html.twig
{{response}}
结果是这样的:
{"status":"200","data":{"is_auth":true,"userToken":"194b873c004716acb3e0a5fba09fe405"}}
但是如果我输入html:
return $this->render('esterne/post.html.twig', array(
'response'=>$response->getBody(),
));
导致错误 500 内部服务器错误
[2018-11-14 09:56:35] request.CRITICAL:未捕获的 PHP 异常 Twig_Error_Runtime:“在渲染模板期间引发了异常(“可捕获的致命错误:GuzzleHttp\Psr7\Response 类的对象无法转换为字符串")。"在 /app/app/Resources/views/esterne/post.html.twig 第 1 行 {"exception":"[object] (Twig_Error_Runtime(code: 0): 在渲染模板期间抛出异常 (\"可捕获的致命错误:GuzzleHttp\Psr7\Response 类的对象无法转换为字符串\")。在 /app/app/Resources/views/esterne/post.html.twig:1,ErrorException(代码:0):可捕获致命错误:GuzzleHttp\Psr7\Response 类的对象无法转换为 /app/var/cache/prod/twig/47/478ca9f9b0a5c69caa7b0fed874bf831466230764635f396f057dc2c33868549.php:23) 处的字符串"} []
解决方案
使用文件
{{ response|json_encode()|raw }}
在树枝和
return $this->render('esterne/post.html.twig', array(
'response'=>json_decode($response->getBody()->getContents(), FALSE),
));
【问题讨论】:
-
将您的响应转换为 json 响应。
-
像这样??创建 JSON 响应¶ symfony.com/doc/current/components/http_foundation.html