2017-04-27 82 views
0

Yii2,基本模板,版本控制。 我想寫一個方法,將返回令牌。Yii2 REST。如何發送post請求到動作索引

還有就是我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; 
     } 
    } 
} 

和配置:

'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>', 
        ], 

       ], 

當我送post請求api.site.ru/v1/token服務器返回: enter image description here

而對於一個完全相同的方法actionLogin服務器退貨: enter image description here

回答

2

默認情況下,POST模式會創建一條規則以指向create操作。這就是Yii試圖在你的控制器中找到create動作的原因。有關更多詳細信息,請參見here

我還沒有測試過它,但是您應該將index方法重命名爲create,或者覆蓋像這樣的默認模式;

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

說真的,'actionCreate'而不是'actionIndex'的工作原理 –

+0

很好用。我猜這是因爲它的工作原理通常是'POST'數據試圖創建一些東西,不管它是什麼,所以它是默認設置。你應該可以覆蓋該設置,但如果它不適合你的用例 –