在 laravel 中处理 guzzle 6 响应主体
Handling guzzle 6 response body in laravel
我正在制作一个与本地 API 通信的 Laravel 5.2 项目。我在处理 Guzzle 响应主体时遇到问题。
我的控制器:
public function getClients(){
$guzzle = new Client();
try{
$response = $guzzle->request('GET', 'http://localhost:3000/client')->getBody();
return view('home.clients', ['clients' => $response]);
}catch(ClientException $e){
//Handling the exception
}
}
我的 blade 查看:
<h2>Client list</h2>
{{ $clients }}//Just to inspect it
@forelse ($clients as $client)
<h3>{{ $client->name }}</h3>
<h3>{{ $client->email }}</h3>
<h3>{{ $client->country }}</h3>
@empty
<h3>No clients here</h3>
@endforelse
循环或控制器上没有错误,也在浏览器中显示流 Object 但在循环中不显示任何内容。
我已经阅读了 Guzzle 6 响应主体文档,但对于像我这样的新手来说还不是很清楚。
想法?
浏览器输出:
您必须使用 json_decode()
:
解码此 JSON
public function getClients(){
$guzzle = new Client();
try {
$response = json_decode($guzzle->request('GET', 'http://localhost:3000/client')->getBody());
return view('home.clients', ['clients' => $response]);
} catch(ClientException $e){
//Handling the exception
}
}
并且您可以从视图中删除 {{ $clients }}//Just to inspect it
。
有关 JSON 和 Guzzle 的更多信息,请点击此处:
我正在制作一个与本地 API 通信的 Laravel 5.2 项目。我在处理 Guzzle 响应主体时遇到问题。
我的控制器:
public function getClients(){
$guzzle = new Client();
try{
$response = $guzzle->request('GET', 'http://localhost:3000/client')->getBody();
return view('home.clients', ['clients' => $response]);
}catch(ClientException $e){
//Handling the exception
}
}
我的 blade 查看:
<h2>Client list</h2>
{{ $clients }}//Just to inspect it
@forelse ($clients as $client)
<h3>{{ $client->name }}</h3>
<h3>{{ $client->email }}</h3>
<h3>{{ $client->country }}</h3>
@empty
<h3>No clients here</h3>
@endforelse
循环或控制器上没有错误,也在浏览器中显示流 Object 但在循环中不显示任何内容。
我已经阅读了 Guzzle 6 响应主体文档,但对于像我这样的新手来说还不是很清楚。
想法?
浏览器输出:
您必须使用 json_decode()
:
public function getClients(){
$guzzle = new Client();
try {
$response = json_decode($guzzle->request('GET', 'http://localhost:3000/client')->getBody());
return view('home.clients', ['clients' => $response]);
} catch(ClientException $e){
//Handling the exception
}
}
并且您可以从视图中删除 {{ $clients }}//Just to inspect it
。
有关 JSON 和 Guzzle 的更多信息,请点击此处: