【发布时间】:2020-02-06 18:54:21
【问题描述】:
场景1发送x-www-form-urlencoded数据
POST /path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar
运行print_r($request->getParsedBody()); 返回正常:
Array
(
[foo] => bar
)
运行print_r($request->getBody()->getContents());会返回一个字符串foo=bar
场景2发送application/json数据
POST /path HTTP/1.1
Content-Type: application/json
{
"foo": "bar"
}
运行 print_r($request->getParsedBody()); 返回一个空数组。 Array ( )
但是,运行 print_r($request->getBody()->getContents()); 返回正常:
{"foo":"bar"}
这是预期的行为吗?
意思是,如果我们发送x-www-form-urlencoded数据,我们应该使用getParsedBody()。
如果我们发送application/json,则应该使用getBody()->getContents()?
其他信息:
请求对象的创建使用:
$request = \Laminas\Diactoros\ServerRequestFactory::fromGlobals(
$_SERVER, $_GET, $_POST, $_COOKIE, $_FILES
);
【问题讨论】:
-
1) 您使用的是哪个 PSR-7 库 - 可能是 zend diactoros? 2) 对于每个场景,您应该提供构建 ServerRequest 对象的代码。 3) 对于“场景 1”:您是否也尝试过使用类似
$content = (string) ($request->getBody()); echo $content;的方式激活StreamInterface::__toString方法?我问这个是因为StreamInterface::__toString方法实现“必须在读取数据之前尝试寻找流的开头”,而StreamInterface::getContents仅“返回剩余的 字符串中的内容". -
@dakis 实际上,场景 1 似乎在使用
$request->getBody()->getContents()时实际上返回了一个字符串foo=bar。我已经更新了场景。还包括如何创建请求对象。
标签: php json post http-post psr-7