Q
Q
qazwerhood2020-01-29 10:05:53
Yii
qazwerhood, 2020-01-29 10:05:53

Why empty POST in YII2 after reinstall?

We developed our own api for mobile applications, which works based on post requests, but after reinstalling the project on a new server, Yii::$app->request->post() always returns an empty value. At the same time, Yii::$app->request->getRawBody() contains a value, but I would not want to rewrite all api.

Tell me what could be the problem and in which direction to dig? Thanks in advance.

Sending via mobile app or post via PHPStorm's RestClient. Returns emptiness always.

public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['login'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['login'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'login' => ['post', 'get'],
                    'token' => ['post', 'get'],
                    'logout' => ['post', 'get'],
                ],
            ],
        ];
    }

public function beforeAction($action) {
        $this->enableCsrfValidation = false;
        return parent::beforeAction($action);
    }

 public function actionLogin()
    {
        return Yii::$app->request->post("username");
    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
wolfak, 2020-02-06
@qazwerhood

Try reinstalling Yii2 again in the correct order, it worked for me.
https://www.yiiframework.com/doc/guide/2.0/ru/star...

D
Dmitry Kim, 2020-01-29
@kimono

Add a JsonParser parser to the request component.
For application/json requests, $_POST will be populated with JSON data automatically.

'components' => [
    'request' => [
        'csrfParam' => '_csrf-api',
        'parsers' => [
            'application/json' => [
                'class' => \yii\web\JsonParser::class,
                'asArray' => true,
            ],
        ],
    ],
// ...

Those. if the input is the following:
{
    "name": "Nick"
}

that $name = Yii::$app->request->post('name')will work.

A
Andrey Lamzin, 2020-01-29
@Byte255

Most likely, for some reason, the data came to the old server as form / data, and on the new server they began to come as application / json.
Why this could happen, I have no idea.
I would patch Yii::$app->request->post() as a quick fix so that it returns data received from Yii::$app->request->getRawBody() and then think further.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question