发送数据时,在Yii2中出现空值,为什么会这样?数据发布:id, name.
JS
let is = document.querySelector("meta[name='csrf-token']").content,
ss = document.querySelector("meta[name='csrf-param']").content;
fetch("http://site.se/react/save-babysitter", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"csrf-param": ss,
"X-CSRF-Token": is
},
body: JSON.stringify({
'id': e.id,
'name': this.state.ChangeName
})
}).then(response => response.json())
.then((data) => console.log(data));
PHP
public function actionSaveBabysitter() {
$request = Yii::$app->request;
$post = $request->post('name');
echo json_decode($post);
}
代码200,post null
默认情况下,Yii从$_POST
全局变量读取post参数。但是web服务器只将发送的主体请求解析为application/x-www-form-urlencoded
或multipart/form-data
。如果你用Content-Type: application/json
发送数据,它们不会被解析成$_POST
变量。
要强制Yii解析JSON请求,必须在yiiwebRequest::$parsers
属性中添加JSON解析器。
你可以这样做,例如在你的web.php
配置文件:
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yiiwebJsonParser',
],
// ... other configurations for request component
],
// ... other components
]