我正在使用Guzzle HTTP在laravel中遇到一个奇怪的错误。我在localhost中有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放在不同的服务器(物理上分开的服务器)下,它可以正常工作!
我有同样的问题。经过一些研究,我发现问题来自'phpdotenv'。有关更多详细信息,请参阅此链接:Laravel environment variables leaking between applications when they call each other through GuzzleHttp
然后我继续研究'phpdotenv'的问题跟踪器,我发现了这个:qazxsw poi
php artisan config:使用laravel时缓存是一个很好的建议;我们还需要另一种分离的phpdotenv解决方案;这是一个恼人的错误。等候...@_@
对于我的情况,我最终运行“php artisan config:cache”作为临时解决方案。
[编辑]我在上一篇文章中发现了一个更好的解决方案:https://github.com/vlucas/phpdotenv/issues/219
因此,不要在应用程序的任何地方调用env函数,而是调用函数config,并在config部分中添加变量。