Zhi V
Zhi V

Reputation: 364

Yii2 REST. How to send post request to actionIndex

Yii2, basic template, versioning. I'm trying to write a method that will give back token.

There is my TokenController:

class TokenController extends Controller
{
public function actionIndex()
    {
        $model = new LoginForm();
        $model->load(Yii::$app->request->bodyParams, '');
        if ($token = $model->auth()) {
            return $token;
        } else {
            return $model;
        }
    }
}

and config:

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => true, 
            'rules' => [
                ''=>'site/index',
            [
                    'class' => 'yii\rest\UrlRule',
                    'pluralize' => false, 
                    'controller' => [
                        'v1/token'
                    ],
                    'extraPatterns' => [
                        'GET <action>'=>'<action>',
                        'POST <action>'=>'<action>',
                    ],

                ],

When I send post request to api.site.ru/v1/token server returns: enter image description here

And for an absolutely identical method actionLogin server returns: enter image description here

Upvotes: 0

Views: 1056

Answers (1)

Joe Miller
Joe Miller

Reputation: 3893

By default the POST pattern creates a rule to direct to a create action. This is why Yii is trying to find a create action in your controller. See here for more details.

I've not tested it, but you should either rename your index method to create, or override the default patterns like this;

'patterns' => [
    'POST'=>'index',
],

Upvotes: 2

Related Questions