yiii2中开发的接口,在postman中使用x-www-format-unencoded的格式进行post请求测试,可以正确返回想要的结果。
但是选用content-type为text/json时,yii控制器中根本没有获取到数据,怎么设置呢。
1.
需要在yii2的配置文件的components 中的request数组里加上以下的转换器:
‘parsers’ => [
‘application/json’ => ‘yii\web\JsonParser’,
‘text/json’ => ‘yii\web\JsonParser’,
]
这样YII2才会根据content-type里的内容寻找正确的转换器。
2.用php://input接收
$post = @file_get_contents('php://input');
//获取请求体,@的作用为屏蔽警告,可去除。
$post = json_decode( $post, true );
//解析成数组