7

我正在使用Slim Framework Version 3并且遇到了一些问题。

$app-> post('/', function($request, $response){
  $parsedBody = $request->getParsedBody()['email'];
  var_dump($parsedBody);
});

结果总是:

空值

你能帮助我吗 ?

4

4 回答 4

25

当我切换到 slimframework 版本 4 时,我必须添加:

$app->addBodyParsingMiddleware();

否则,body 总是为 null(甚至 getBody())

于 2019-11-12T22:04:27.360 回答
5

这取决于您如何将数据发送到路由。这是一个 POST 路由,因此默认情况下它将期望正文数据为标准表单格式 ( application/x-www-form-urlencoded)。

如果要将 JSON 发送到此路由,则需要将Content-type标头设置为application/json. 即卷曲看起来像:

curl -X POST -H "Content-Type: application/json" \
  -d '{"email": "a@example.com"}' http://localhost/

此外,您应该验证您正在寻找的数组键是否存在:

$parsedBody = $request->getParsedBody()
$email = $parsedBody['email'] ?? false;
于 2017-02-17T09:12:29.567 回答
1

请尝试这种方式:

$app-> post('/yourFunctionName', function() use ($app) {
  $parameters = json_decode($app->request()->getBody(), TRUE);
  $email = $parameters['email'];
  var_dump($email);
});

我希望这可以帮助你!

于 2017-02-14T07:42:07.760 回答
1

在 Slim 3 中,您必须为此注册一个 Media-Type-Parser 中间件。

http://www.slimframework.com/docs/v3/objects/request.html

$app->add(function ($request, $response, $next) {
    // add media parser
    $request->registerMediaTypeParser(
        "text/javascript",
        function ($input) {
            return json_decode($input, true);
        }
    );

    return $next($request, $response);
});
于 2019-09-30T08:15:12.783 回答