Guzzle 无法向本地主机发出 GET 请求(端口:80、8000、8080 等)

Yus*_*him 2 php http laravel guzzle laravel-artisan

目前使用 Laravel 5.5 和与 Laravel 安装程序一起提供的 Guzzle。

我正在尝试发出 GET 请求(其他 HTTP 请求也会发生错误),但似乎不起作用。

此代码不起作用:

public function callback(Request $request)
{
    $code = $request->code;

    $client = new Client(['exceptions' => false]);

    try {
      $response = $client->request('GET', 'http://localhost/api/tests');
        // $response = $http->request('POST', Config::get('app.url') . '/oauth/token', [
        //     'form_params' => [
        //         'grant_type' => 'authorization_code',
        //         'client_id' => Config::get('oauth_client.client_id'),
        //         'client_secret' => Config::get('oauth_client.client_secret'),
        //         'redirect_uri' => Config::get('oauth_client.redirect_uri'),
        //         'code' => $code,
        //     ],
        // ]);
        // return json_decode((string) $response->getBody(), true);
    } catch (\Exception $e) {
        dd($e);
    }
    dd($response->getBody());
    return;
}
Run Code Online (Sandbox Code Playgroud)

但是下面的这段代码工作得很好

public function callback(Request $request)
{
    $code = $request->code;

    $client = new Client(['exceptions' => false]);

    try {
      $response = $client->request('GET', 'https://www.google.co.id');
        // $response = $http->request('POST', Config::get('app.url') . '/oauth/token', [
        //     'form_params' => [
        //         'grant_type' => 'authorization_code',
        //         'client_id' => Config::get('oauth_client.client_id'),
        //         'client_secret' => Config::get('oauth_client.client_secret'),
        //         'redirect_uri' => Config::get('oauth_client.redirect_uri'),
        //         'code' => $code,
        //     ],
        // ]);
        // return json_decode((string) $response->getBody(), true);
    } catch (\Exception $e) {
        dd($e);
    }
    dd($response->getBody());
    return;
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我的 Guzzle 能够请求 google.com 但无法连接到我自己的本地主机服务器(到所有端口)。

任何帮助将不胜感激。

谢谢,

Fri*_*ich 6

它不工作的原因是php artisan serve使用 PHP 内置的 web 服务器,这是单线程的。因此,如果您运行您的应用程序,它在完成初始请求之前无法发出另一个请求(您的 Guzzle 请求)。这就是为什么它挂起(如提到这里)。

一种解决方案是(如您所指出的)使用真正的多线程网络服务器。

但是如果你仍然想使用php artisan serve像 Nginx 这样的网络服务器,有一个简单的解决方案(我已经在另一个问题中发布了):

您可以使用另一个端口运行另一个 Web 服务器实例,并配置您的应用程序以base_uri在连接到 API 时使用它:

php artisan serve \\ defaults to port 8000
\\ in another console
php artisan serve --port=8001
Run Code Online (Sandbox Code Playgroud)
php artisan serve \\ defaults to port 8000
\\ in another console
php artisan serve --port=8001
Run Code Online (Sandbox Code Playgroud)

  • 对于 php7.4,我们可以使用以下命令: PHP_CLI_SERVER_WORKERS=10 php artisanserve --port=80 --host 0.0.0.0 (2认同)