为什么消息没有 POST
Why doesn't the message POST
Yii2发送数据时出现空值,这是为什么?
数据post: 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 空
Yii 默认从 $_POST
全局变量中读取 post 参数。但是 web 服务器只解析正文发送的请求为 application/x-www-form-urlencoded
或 multipart/form-data
。如果您使用 Content-Type: application/json
发送数据,它们不会被解析为 $_POST
变量。
要强制 Yii 解析 JSON 请求,您必须将 json 解析器添加到 yii\web\Request::$parsers
属性.
例如,您可以在 web.php
配置文件中执行此操作:
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
// ... other configurations for request component
],
// ... other components
]
Yii2发送数据时出现空值,这是为什么? 数据post: 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 空
Yii 默认从 $_POST
全局变量中读取 post 参数。但是 web 服务器只解析正文发送的请求为 application/x-www-form-urlencoded
或 multipart/form-data
。如果您使用 Content-Type: application/json
发送数据,它们不会被解析为 $_POST
变量。
要强制 Yii 解析 JSON 请求,您必须将 json 解析器添加到 yii\web\Request::$parsers
属性.
例如,您可以在 web.php
配置文件中执行此操作:
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
// ... other configurations for request component
],
// ... other components
]