Slim - 修改中间件内的 POST 请求正文 [英] Slim - modify POST request body inside middleware

查看:51
本文介绍了Slim - 修改中间件内的 POST 请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Slim v3justinrainbow 的 json 模式验证器 用于我的 API.我想做但不能上班的是:

I am using Slim v3 and the json schema validator by justinrainbow for my API. What I want to do and just can't get to work is:

  • 在中间件中:使用默认值验证传入的 json.这会产生一个修改过的对象
  • 将修改后的对象写回到请求中,以便核心控制器可以对其进行处理

我不擅长的是:

# inside middleware:
$requestbody = $request->getBody();
$requestobject = json_decode($requestbody);
# validation and modification of $requestobject takes place here
$request->getBody()->write(json_encode($requestobject));
$request->reparseBody();
return $next($request, $response);

从那时起,请求正文只是null.我究竟做错了什么?我很确定我修改 Slim 对象的方式有问题,因为当我手动尝试 $request->getBody()->write('{"some": "content"}') 也是如此.

From that point on, the request body is just null. What am I doing wrong? I am rather certain that there is something wrong with the way I am modifying Slim objects, because it does not work when I manually try $request->getBody()->write('{"some": "content"}') as well.

推荐答案

解决方案是withParsedBody():

The solution was withParsedBody():

# inside middleware:
$requestbody = $request->getBody();
$requestobject = json_decode($requestbody);

# validation and modification of $requestobject takes place here

$request = $request->withParsedBody($requestobject);
return $next($request, $response);

正如我所需要的那样,它用修改后的对象完全覆盖了请求正文.您需要注意的事项:

It completely overwrites the request body with the modified object, just as I needed. What you have to pay mind to:

  • 从那时起,请求将保存一个已解析的对象作为正文,并且在调用 $request->getParsedBody() 时,如果我正确理解源代码,它将不会被重新解析
  • 在调用 $request->getParsedBody() 时,如果主体是 JSON,你通常会得到一个关联数组,但使用上面的代码片段,解析后的主体将是一个对象.
  • From there on, the request will hold a parsed object as body and on calling $request->getParsedBody() it won't be reparsed, if I understand the source correctly
  • on calling $request->getParsedBody() you usually get an associative array if the body was JSON, but using the snippet above, the parsed body will be an object instead.

愿这段代码对未来的用户有所帮助.

May the snippet be helpful to users in the future.

这篇关于Slim - 修改中间件内的 POST 请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆