赶知识网

GuzzleHttp\Client忽略base_url中的基本路径

2023-07-06 / 398次点击 php/mysql/apache GuzzleHttp

在一组PHPUnit驱动的REST API测试中使用Guzzle.


我创建我的客户端如下:


use GuzzleHttp\Client;


$client = new Client(['base_url' => ['http://api.localhost/api/{version}', ['version' => '1.0']]]);

这工作正常,我可以使用以下代码发出请求:


$request = $client->createRequest('GET', '/auth');

$request->setBody(Stream::factory(json_encode(['test'=>'data'])));

$response = $client->send($request);

$decodedResponse = $response->json();

但是,Guzzle忽略了/api/{version}基本URL 的一部分并向此处发出请求:


http://api.localhost/auth

但是,我原以为它会在这里提出请求:


http://api.localhost/api/1.0/auth

难道我错阅读文档和我预期的行为是错误的.因此,还是有一些其他的选择,我需要能够得到它的追加/authURL的/api/1.0基本路径提出请求时?

以下是Michael Dowling所写的Guzzle 7( 7.4.1)示例

$client = new Client(['base_uri' => 'http://my-app.com/api/']);

$response = $client->get('facets'); // no leading slash - append to base

//    http://my-app.com/api/facets


$client = new Client(['base_uri' => 'http://my-app.com/api/']);

$response = $client->get('facets/'); // no leading slash - append to base // ending slash preserved

//    http://my-app.com/api/facets/


$client = new Client(['base_uri' => 'http://my-app.com/api/']);

$response = $client->get('/facets'); // leading slash - absolute path - base path is lost

//    http://my-app.com/facets


$client = new Client(['base_uri' => 'http://my-app.com/api']); // no ending slash in base path - ignored

$response = $client->get('facets');

//    http://my-app.com/facets


$client = new Client(['base_uri' => 'http://my-app.com/api']);

$response = $client->get('/facets'); // leading slash - absolute path - base path is lost

//    http://my-app.com/facets


有用 没用

Top10

沪ICP备09053415号 © 赶知识网