Laravel - 即使 URL 正确,Guzzle 也不会返回任何数据

Laravel - Guzzle not returning any data even though URL is correct

我正在尝试 return 来自第三方的 JSON 数据 API - http://postcodes.io/。我目前在我的控制器中有:

 $client = new Client();
    $request = $client
        ->get('https://api.postcodes.io/postcodes/'.Input::get('postcode'));

    $statusCode = $request->getStatusCode();

    if ($statusCode >= 200 && $statusCode < 300) 
    {
       $json = Response::json($request); // Returns JSON decoded array of data.
    }

我正在尝试 return 邮政编码信息:

https://api.postcodes.io/postcodes/OX495NU

如果我 dd($request),则会打印出带有 200 状态代码但没有与之关联的数据:

JsonResponse {#245 ▼
  #jsonOptions: 0
  #data: "{}"
  #callback: null
  #encodingOptions: 15
  +headers: ResponseHeaderBag {#242 ▶}
  #content: "{}"
  #version: "1.0"
  #statusCode: 200
  #statusText: "OK"
  #charset: null
}

对于为什么会发生这种情况的任何帮助,我们将不胜感激。

您看到的是 Guzzle 返回的原始响应,需要对其进行格式化。一个简单的方法是$response->getBody();

可以把它想象成 Laravel 中的 collection。当你取回数据时,它在 collection 中,其中包含一堆可能有用的额外数据,但如果你只想要数据,你会 运行 $user->toJson(); For Guzzle,如果你想去除所有额外的 curl 数据、协议信息、headers 等,你只需要有效负载,或 body。 $response->getBody();