Har*_*ari 5 laravel guzzle laravel-5.4
我在 Laravel 和 Guzzle HTTP 中遇到了一个奇怪的错误。我的本地主机中有 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')]);
Run Code Online (Sandbox Code Playgroud)
如果我直接在浏览器上调用 APP2 url,它会返回正确的结果:
{"host":"localhost","env_host":"localhost"}
Run Code Online (Sandbox Code Playgroud)
但是如果我通过 Guzzle HTTP 从 APP1 到 APP2 进行 REST 调用,它会返回以下响应:
{"host":"localhostX","env_host":"localhostX"} //where localhostX is the value I added in .env file of APP1
Run Code Online (Sandbox Code Playgroud)
这是 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);
Run Code Online (Sandbox Code Playgroud)
有人能解决这个问题吗?我认为 guzzle 使 REST 不保持会话。
我已经在此处提到了问题和答案Getting Trouble while moving http request from one laravel project to another in the same machine在这里。但我没有看到该问题的正确解决方案。
laravel 版本:5.4 laracast 链接:https://laracasts.com/discuss/channels/laravel/laravel-guzzle-http-return-wrong-response
如果我将 APP1 和 APP2 放在不同的服务器(物理上分离的服务器)下,它会按预期正常工作!
我有同样的问题。经过一些研究,我发现问题来自“phpdotenv”。有关更多详细信息,请参阅此链接:Laravel 环境变量在应用程序之间通过 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 并将变量添加到配置部分。
| 归档时间: |
|
| 查看次数: |
2250 次 |
| 最近记录: |