在同一系统上从一个 laravel 应用程序向另一个应用程序进行 Guzzle Http 调用时出现问题

Issue when make Guzzle Http call from one laravel app to another on same system

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

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

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

如果我直接在浏览器上调用APP2url,它return正确的结果:

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

但是如果我通过 Guzzle HTTP 从 APP1 到 APP2 进行 REST 调用,它 return 的响应是:

{"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 不保持会话。

我已经在这里提到了问答。但是我没有看到问题的正确解决方案。

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

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

我遇到了完全相同的问题。 经过一些研究,我发现问题出在 'phpdotenv'。有关详细信息,请参阅此 link:

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

php artisan config:cache is a good suggestion when using laravel; We also need another solution for separated phpdotenv; It is an annoying bugs. Waiting...@_@

对于我的情况,我最终 运行 "php artisan config:cache" 作为临时解决方案。

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

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