Skip to content
Advertisement

Why doesn’t the message POST

When sending data, an empty value comes in Yii2, why is that? Data 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);

}

Code 200, post null

Advertisement

Answer

By default the Yii reads post params from $_POST global variable. But web server only parses request of body send as application/x-www-form-urlencoded or multipart/form-data. If you send data with Content-Type: application/json they are not parsed into $_POST variable.

To force Yii parsing JSON request you have to add json parser into yiiwebRequest::$parsers property.

You can do that for example in your web.php config file:

'components' => [
    'request' => [
        'parsers' => [
            'application/json' => 'yiiwebJsonParser',
        ],
        // ... other configurations for request component
    ],
    // ... other components 
]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement