Yii2: Method Not Allowed (#405) while logout user
You can also use a custom template
'items' => [
[
'label' => 'Logout',
'url' => ['/user/security/logout'],
'template' => '<a href="{url}" data-method="post">{label}</a>',
],
]
You must only replace 'logout' => ['post'], with 'logout' => ['get']. In this way your error will be solved.
This way works only with Yii Framework version 2.
- See more at: http://tutorials.scrisoft.com/solve-this-error-method-not-allowed-this-url-can-only-handle-the-following-request-methods-post/#sthash.fQmwYPJH.dpuf
u can change the view code and echo instead of
<li>
<a href="<?= Url::to(['site/logout'])?>">
<i class="fa fa-sign-out"></i> Log out
</a>
</li>
this one:
<?= Html::a('<i class="fa fa-sign-out"></i>',
['/site/logout'],
['class'=>'btn btn-default btn-flat']), //optional* -if you need to add style
['data' => ['method' => 'post',]])
?>
Seems like you have VerbFilter
attached to logout
action in your SiteController
:
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
That means this action can requested only with POST method, and you are requesting with GET, that's why exception #405 is thrown.
Either remove this from VerbFilter
or add data-method
attribute to request with POST:
<a href="<?= Url::to(['site/logout'])?>" data-method="post">...</a>
Update: Another reason of this problem can be missing dependency for yii\web\YiiAsset. Make sure it's included in AppAsset
:
public $depends = [
'yii\web\YiiAsset',
...
];
YiiAsset
provides data-method
attribute feature which gives possibility to link act as a form with action post
by writing less code. Without asset obviously link will act as regular link and standard GET request will be sent.