T
T
Timur Tuz2016-06-26 11:15:12
JavaScript
Timur Tuz, 2016-06-26 11:15:12

Yii2 does not parse json requests. How to win?

Colleagues prompt on a question. Send json in ajax request:

var register_headers = new Headers();
register_headers.append('Content-type', 'application/json');
var headers = {headers: register_headers};
return new Promise((resolve) => {
  this._http.post('http://localhost/auth/login', JSON.stringify({username: 'username',password: 'password'}), headers)
.subscribe((data) => {if (data.json().success) {...}})
        })

with the header "'Content-type', 'application/json'"
Yii2 does not see this data in
Yii::$app->getRequest()->getBodyParams()
Judging by the docs, you need to write in the config for this:
'components' => [
        'request' => [
            'parsers' => [
                'application/json' => 'yii\web\JsonParser'

I did but didn't help. at the same time, this code parses everything normally
$body = json_decode(Yii::$app->getRequest()->getRawBody(), true);

I can't understand shit

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Tuz, 2016-07-14
@TTA

in general, the issue was resolved. It turned out that when cross-domain requests through the browser are sent with json data and the "'Content-type application/json" header, they are converted from post to options.
in Yii I set that the "text/plain" request is perceived as REST, removed the header in js and everything worked.

V
vacoo, 2016-06-26
@vacoo

You need to send an object as data in the ajax request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question