我试图使用邮递员从yii2的前端发帖,但我得到了这个
{
"name": "Method Not Allowed",
"message": "Method Not Allowed. This url can only handle the following request methods: GET, HEAD.",
"code": 0,
"status": 405,
"type": "yii\\web\\MethodNotAllowedHttpException"
}
我不知道如何从前端发帖。
这是我的前端控制器代码
class TestController extends ActiveController {
public $modelClass = 'common\models\Test';
public function behaviors(){
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page', 'X-Pagination-Page-Count'],
],
];
return $behaviors;
}
public function actions(){
$actions = parent::actions();
unset($actions['index']);
return $actions;
}
public function actionIndex(){
$activeData = new ActiveDataProvider([
'query' => Test::find()->orderBy('test_id DESC'),
'pagination' => [
'defaultPageSize' => 5,
]
]);
return $activeData;
}
}
我对编程很陌生,需要一个非常简单的解释和示例来说明如何允许post方法。
答案 0 :(得分:0)
好吧,好像你从\yii\rest\ActiveController
继承了你的控制器。它具有verbs()
方法,您必须在控制器中覆盖该方法以为其提供适当的方法。这是来自原始班级的verbs()
:
protected function verbs()
{
return [
'index' => ['GET', 'HEAD'],
'view' => ['GET', 'HEAD'],
'create' => ['POST'],
'update' => ['PUT', 'PATCH'],
'delete' => ['DELETE'],
];
}
尝试在TestController中编写类似的内容:
protected function verbs() {
$verbs = parent::verbs();
$verbs['index'] => ['POST']; //methods you need in action
//or
$verbs['index'][] => 'POST'; //just add the 'POST' to "GET" and "HEAD"
return $verbs;
}