我在使用 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);
任何人都可以解决这个问题吗?我认为暴饮暴食使 REST 不保持 session 。
我已经在这里提到了 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 放在不同的服务器(物理分离的服务器)下,它会按预期正常工作!!
最佳答案
我有同样的问题。
经过一些研究,我发现问题来自'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 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”作为临时解决方案。
[编辑]
我在这个链接上找到了一个更好的解决方案,在最后一篇文章中:
https://laracasts.com/discuss/channels/general-discussion/env-not-reading-variables-sometimes
因此,不要在应用程序的任何地方调用 env 函数,而是调用函数 config 并在 config 部分添加变量。
关于laravel - 在同一系统上从一个 Laravel 应用程序向另一个应用程序进行 Guzzle Http 调用时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49954397/