Request parameters are empty using Slim v4.1(使用Slim v4.1时,请求参数为空)
本文介绍了使用Slim v4.1时,请求参数为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将Slim v4
用于一个小的Arduino组件API。当我在我的控制器上执行POST
调用时,我得到一个空的请求正文,没有我发送给它的参数。
在下面的代码中,在$parameters
变量i中有一个空。
public function __invoke(
ServerRequestInterface $request,
ResponseInterface $response
) : ResponseInterface {
$ret = [
'success' => false
];
$parameters = (array) $request->getParsedBody();
}
我正在使用postman
执行CURL
请求,但在bash中使用curl
时也会显示此错误。
下面的代码是我注册新API调用的方式。
$application = AppFactory::create();
$application->group('/ambient', function(RouteCollectorProxy $routeCollector) {
$routeCollector
->post('/register', RegisterAmbientController::class)
->setName('register-ambient');
});
您还可以在My GitHub中查看完整代码: https://github.com/JasterTDC/ardu-component/tree/feature/register-temp-humidity
提前谢谢!
推荐答案
Slim 4不会自动解析正文,除非它是基于表单的POST请求。如果您的有效负载是POST或PUT中的JSON或XML,那么您将需要一些正文解析中间件。
BodyParsingMiddleware
为超薄4添加了yesterday。
$app
实例后添加$app->addBodyParsingMiddleware();
。类似这样的工作方式:
use PsrHttpMessageResponseInterface;
use PsrHttpMessageServerRequestInterface;
use SlimFactoryAppFactory;
use SlimMiddlewareBodyParsingMiddleware;
use SlimPsr7Response;
$app = AppFactory::create();
$app->addBodyParsingMiddleware();
$app->post('/data', function (ServerRequestInterface $request): ResponseInterface {
$data = $request->getParsedBody();
$response = new Response();
$response->getBody()->write(
print_r($data, true)
);
return $response;
});
$app->run();
但是请注意,您需要在您的Composer.json中使用dev-4.x
,或者等待4.1之后的下一个次要版本。
这篇关于使用Slim v4.1时,请求参数为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用Slim v4.1时,请求参数为空
基础教程推荐
猜你喜欢
- 超薄框架REST服务两次获得输出 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01