Slim 4. POST 请求正文为空

发布于 2025-01-15 12:41:12 字数 974 浏览 2 评论 0原文

我使用 POST 方法创建了路线。当我发送带有正文的请求,但我尝试使用时

$request->getParsedBody()

,我总是采用 NULL。为什么?

<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
 
require __DIR__ . '/../vendor/autoload.php';
 
$app = AppFactory::create();
$app->addErrorMiddleware(true, false, false);
 
$app->post('/add', function (Request $request, Response $response, array $args) {
    $data = $request->getParsedBody();
 
    return $response;
});
 
$app->run();

邮递员的请求

POST /test HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache

{
    "name": "test",
    "email": "[email protected]"
}

I created route with method POST. When i send request with body, but i trying use

$request->getParsedBody()

I am always takes NULL. Why?

<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
 
require __DIR__ . '/../vendor/autoload.php';
 
$app = AppFactory::create();
$app->addErrorMiddleware(true, false, false);
 
$app->post('/add', function (Request $request, Response $response, array $args) {
    $data = $request->getParsedBody();
 
    return $response;
});
 
$app->run();

Request from Postman

POST /test HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache

{
    "name": "test",
    "email": "[email protected]"
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

追我者格杀勿论 2025-01-22 12:41:12

尝试添加正文解析中间件

$app->addBodyParsingMiddleware();

Try to add the Body Parsing Middleware

$app->addBodyParsingMiddleware();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文