【问题标题】:Handling guzzle 6 response body in laravel在 laravel 中处理 guzzle 6 响应体
【发布时间】:2016-05-12 00:30:53
【问题描述】:

我正在制作一个与本地 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
    }
}

我的刀片视图:

<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

循环或控制器上没有错误,也在浏览器中显示流对象,但在循环中不显示任何内容。

我已经阅读了 Guzzle 6 响应正文文档,但对于像我这样的新手来说,这并不是很清楚。

想法?

浏览器输出:

【问题讨论】:

    标签: php laravel guzzle6


    【解决方案1】:

    您必须使用 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 的信息在这里:Guzzle 6: no more json() method for responses

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 2017-10-24
      • 2016-03-08
      • 2020-09-28
      • 1970-01-01
      • 2016-01-20
      • 2016-05-04
      • 2019-08-04
      相关资源
      最近更新 更多