Laravel-无法使用HTTPClient从API获取数据

问题描述 投票:0回答:1

我有一个Angular + Vue应用程序。我想通过Axios使用Laravel控制器将数据管理与前端分开。在此示例中,我使用JSON占位符获取数据。该代码类似于

JS

<script>
export default {
  mounted() {
    axios
      .get("http://127.0.0.1:8000/test")
      .then(response => console.log(response));
  }
};
</script>

路线

Route::resource('test', 'TestController');

TestController

use Illuminate\Support\Facades\Http;

    public function index()
    {
        $response = Http::get('https://jsonplaceholder.typicode.com/posts');
        return response()->json($response);
    }

问题:返回500(内部服务器错误)。如果我用dd('ok')检查控制器功能,则网络(在开发控制台中)响应为'ok',因此我认为这是get方法错误或使用不正确。我使用此documentation作为指导,但这不是一个真实的示例,因此我的代码中出现了某些故障。

那么,有人错了吗?

laravel vue.js axios guzzle
1个回答
0
投票

从您的代码$response中将保留完整的Guzzle响应对象,包括标题,Cookie等。

您可以使用以下方法查看:

$response = Http::get('https://jsonplaceholder.typicode.com/posts');
dd($response); 

您不想返回整个Guzzle响应,而只返回该响应的json()

替换

return response()->json($response);

return $response->json();

阅读有关您已发布的U​​RL的更多信息:https://laravel.com/docs/7.x/http-client

编辑:这很可能不会解决您的500内部服务器错误,而是在解决500之后会返回正确的JSON,请查看您的laravel.log以查看500的原因

© www.soinside.com 2019 - 2024. All rights reserved.