【问题标题】:Issue when make Guzzle Http call from one laravel app to another on same system在同一系统上从一个 laravel 应用程序向另一个应用程序进行 Guzzle Http 调用时的问题
【发布时间】:2018-10-01 22:10:33
【问题描述】:

我在使用 Guzzle HTTP 的 laravel 中遇到了一个奇怪的错误。我的本地主机中有 2 个应用程序 APP1(充当客户端)和 APP2(充当服务器)。 APP1 必须通过 Guzzle HTTP 调用 APP2 来获取数据。当我在 APP1 中调用 URL 时,该操作会调用 APP2 并返回响应。但是如果我们通过这种方式调用,我发现APP2使用了APP1的.env和数据库连接。

为了确认这一点,我在 APP2 的操作中添加了代码。

return response()->json(['host' => DB::connection()->getConfig("host"), 'env_host' => env('DB_HOST')]);

如果我直接在浏览器上调用APP2 url,它会返回正确的结果:

{"host":"localhost","env_host":"localhost"}

但如果我通过 Guzzle HTTP 从 APP1 到 APP2 进行 REST 调用,它会返回以下响应:

{"host":"localhostX","env_host":"localhostX"} //where localhostX is the value I added in .env file of APP1

这是guzzle请求代码:

 client = new Client([ 'base_uri' => 'http://localhost/app2/', 'http_errors' => true, 'allow_redirect' => true ]);

        $response = $this->client->request('GET', $uri, []);

        $responseCode = $response->getStatusCode();
        $contentType  =  $response->getHeaderLine('content-type');
        $responseBody = $response->getBody()->getContents();
        dd($responseBody);

有人可以解决这个问题吗?我认为 guzzle 使 REST 无法保持会话。

我已经在这里提到了问题和答案Getting trouble when sending http request from one laravel project to another in same machine。但我没有看到适当的解决方案。

laravel 版本:5.4 laracast 链接:https://laracasts.com/discuss/channels/laravel/laravel-guzzle-http-return-wrong-response

如果我将 APP1 和 APP2 放在不同的服务器(物理分离的服务器)下,它可以正常工作!

【问题讨论】:

    标签: laravel laravel-5.4 guzzle


    【解决方案1】:

    我也有同样的问题。 经过一些研究,我发现问题来自'phpdotenv'。有关详细信息,请参阅此链接:Laravel environment variables leaking between applications when they call each other through GuzzleHttp

    然后我继续在“phpdotenv”的问题跟踪器中进行研究,发现:https://github.com/vlucas/phpdotenv/issues/219

    php artisan config:cache 在使用 laravel 时是一个很好的建议; 我们还需要另一种分离 phpdotenv 的解决方案; 这是一个令人讨厌的错误。等待中...@_@

    就我而言,我最终将“php artisan config:cache”作为临时解决方案运行。

    [编辑] 我在这个链接上找到了一个更好的解决方案,在最后一篇文章中: https://laracasts.com/discuss/channels/general-discussion/env-not-reading-variables-sometimes

    因此,与其在应用程序的任何位置调用 env 函数,不如调用函数 config 并将变量添加到 config 部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多