【问题标题】:How to retrieve JSON from a API endpoint using Laravel 5.4?如何使用 Laravel 5.4 从 API 端点检索 JSON?
【发布时间】:2017-07-09 00:37:33
【问题描述】:

我有 2 个使用 Laravel 5.4 制作的项目:

  1. Prj-1 是一个返回 JSON 的 Restful API。
  2. Prj-2 是一个使用上述端点的网站。

通过这种方式,我从 Prj-1 获得了以下端点: myAPI.com/city,以 JSON 格式返回数据库中所有城市的列表。

在 Prj-2 中我有以下内容:

Route:
Route::get('/showCityAPItest','AddressController@getcity'); 

Controller:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
...
public function getcity()
    {


        $request =Request::create('http://myAPI.com/city', 'GET');
        $response = Route::dispatch($request);
        dd($response);
    }

如果我在浏览器中直接使用 URL (http://myAPI.com/city),它可以工作。我可以按预期看到 JSON。 但是当我尝试从 Prj-2 中检索它时,我在浏览器中看不到它。

其实我看到了

404 Not Found
nginx/1.10.1 (Ubuntu)

我关注了这个post,但我不知道我做错了什么。

有什么帮助吗?

【问题讨论】:

    标签: laravel api laravel-5


    【解决方案1】:

    是的,@Joel Hinz 是对的。请求将在同一个项目 api 端工作。 您需要使用 GuzzleHttp。 步骤 1. 使用 composer 安装 guzzle。作曲家的 Windows 基础操作 guzzle 命令:

    composer require guzzlehttp/guzzle
    

    第二步编写如下代码

    public function getcity()
        {     
           $client = new \GuzzleHttp\Client;
           $data =$client->request('GET', 'http://myAPI.com/city', [
           'headers' => [
               'Accept'     => 'application/json',
               'Content-type' => 'application/json'
           ]
           ]);
    
           $x = json_decode($data->getBody()->getContents());
           return response()->json(['msg' => $x], 200);
    } 
    

    【讨论】:

      【解决方案2】:

      您所指的答案是关于内部路线。您不能将RequestRoute 外观用于这样的外部地址。相反,使用例如Guzzle (http://docs.guzzlephp.org/en/latest/) 从第二个站点发送您的请求。

      【讨论】:

        猜你喜欢
        • 2018-02-16
        • 1970-01-01
        • 2018-07-17
        • 2019-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-02
        • 2018-03-09
        相关资源
        最近更新 更多