middleware - 如何修改Guzzle中间件中的参数?

标签 middleware guzzle

我想为Guzzle写一个中间件它将特定的键添加到 form_params 并用值填充它。在我读过的文档中how to modify the headers但尚未找到有关 $request 对象其他属性的任何信息。按照文档中的示例,这就是我所拥有的:

$key = 'asdf';

$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::mapRequest(function (RequestInterface $request) use ($key) {

    // TODO: Modify the $request so that
    // $form_params['api_key'] == 'default_value'

    return $request;
}));

$client = new Client(array(
    'handler' => $stack
));

中间件应该修改请求,以便:

$client->post('example', array(
    'form_params' => array(
        'foo' => 'some_value'
    )
));

与此具有相同的效果:

$client->post('example', array(
    'form_params' => array(
        'foo' => 'some_value',
        'api_key' => 'default_value'
    )
));

最佳答案

做过类似的事情后,我可以说这非常简单。

如果您引用 GuzzleHttp\Client 当您将数组传递到“form_params”输入选项中的请求时,会发生两件事。首先,数组的内容在使用 http_build query() 进行 urlencoded 后成为请求的正文,其次,“Content-Type” header 设置为“x-www-form-urlencoded”

下面的代码片段类似于您正在寻找的内容。

$stack->push(Middleware::mapRequest(function (RequestInterface $request) {

    // perform logic


    return new GuzzleHttp\Psr7\Request(
        $request->getMethod(),
        $request->getUri(),
        $request->getHeaders(),
        http_build_query($added_parameters_array) . '&' . $request->getBody()->toString()
    );

}));

关于middleware - 如何修改Guzzle中间件中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32846892/

相关文章:

php - 流明:类 Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse 不存在

php - GuzzleHttp\Client 动态更改基本 URL

laravel - 如何在 PHP 中从 Guzzle Http 获取响应

api - Laravel 5.1 Guzzle - undefined offset : 0

node.js - 如何将附加参数传递给 passport.authenticate

node.js - 在 Mongoose 中更改 pre ('validate' ) 中间件中的字段是否正确?

express - get/post/... 和 use 有什么区别

node.js - 我必须在nodejs中使用bodyParser吗?

php - Guzzle 6下载文件

php - POST 请求适用于 Postman,但不适用于 Guzzle