GuzzleHttp不显示来自nodejs服务器的响应

时间:2019-09-02 03:46:36

标签: php node.js laravel guzzlehttp

我正在使用GuzzleHttp。我想将请求从laravel发送到nodejs。

    try {

        $client = new \GuzzleHttp\Client();
        $url = 'http://localhost:8085/api/test/get';
        $headers = [
            'Accept' => 'application/json',
        ];


        $res = $client->post($url, [
            'headers' => $headers,
            'json' => $data,
        ]);
        dd($res->getBody());
    }
    catch(\Exception $e) {

       echo $e->getMessage();
    }

我的请求也发送了,但是$res->getBody()没有显示我的nodejs结果。 (我肯定nodejs有响应)

我的nodejs代码:

   total_result            = _res.length
    response.total_result   = total_result
    response.result         = _res
    console.log(response)
    res.setHeader('Content-Type', 'application/json')
    res.status(200).json(response); 

dd($res->getBody());的结果是:

Stream {#2694
  -stream: stream resource @1095
    wrapper_type: "PHP"
    stream_type: "TEMP"
    mode: "w+b"
    unread_bytes: 0
    seekable: true
    uri: "php://temp"
    options: []
  }
  -size: null
  -seekable: true
  -readable: true
  -writable: true
  -uri: "php://temp"
  -customMetadata: []
}

1 个答案:

答案 0 :(得分:1)

解决了。您应该使用异步请求:

$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});

$promise->wait();

https://github.com/guzzle/guzzle