symfony - guzzlehttp 和 symfony 与 rest api 问题
问题描述
我想使用guzzlehttp
in使用 rest api 进行 post callsymfony
我
写了这段代码,但响应
/**
* @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),
));
解决方案
您可以尝试以下回复。
return $this->render('esterne/post.html.twig', array(
'response'=>$response->getBody()->getContent(),
));
推荐阅读
- java - 通过后映射将数组从 Spring Boot 传递给 Reactjs 仅返回第一个对象
- html - 如何在 PC 视图上将我的卡作为二进制组
- android-studio - 从 android studio dev env 连接到 Android 模拟器。在 Virtualbox 虚拟机中
- php - PHP中电子表格的时间差异
- python - 将熊猫 0.25.3 升级到 1.3.2
- javascript - 如何从嵌套的对象数组中获取每个父级的值
- javascript - 如何通过 querySelectorAll() 选择所有元素
- caching - 使用 kaniko 构建多阶段图像时的缓存问题
- flutter - 做什么
在 Flutter 代码中是什么意思? - typescript - 以编程方式打开 Material-UI Select 时失去焦点