關於 Yii2 中 RESTful API 的開發,可以參考另一篇隨筆 http://www.cnblogs.com/ganiks/p/yii2-restful-api-dev.html
測試的過程中遇到一個這樣的問題, 報錯 405 yii2 RESTful API 405 Method Not Allowed
比如請求 PUT 方法 的 http://192.168.4.126/news/162?access-token=100-token
{
"type": "yii\\web\\MethodNotAllowedHttpException",
"name": "Method Not Allowed",
"message": "Method Not Allowed. This url can only handle the following request methods: GET, HEAD.",
"code": 0,
"status": 405
}
這里由於不是在 yii2 的前台框架體系中,因此沒有看到堆棧的調試信息,但是要調試也要找到這個報錯 message 的所在:
yii2\filters\VerbFilter.php
public function beforeAction($event)
{
$action = $event->action->id;
if (isset($this->actions[$action])) {
$verbs = $this->actions[$action];
} elseif (isset($this->actions['*'])) {
$verbs = $this->actions['*'];
} else {
return $event->isValid;
}
$verb = Yii::$app->getRequest()->getMethod();
$allowed = array_map('strtoupper', $verbs);
if (!in_array($verb, $allowed)) {
$event->isValid = false;
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7
Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $allowed));
throw new MethodNotAllowedHttpException('Method Not Allowed. This url can only handle the following request methods: ' . implode(', ', $allowed) . '.');
}
return $event->isValid;
}
這里調試打印一下 $action
, 發現每次無論傳入什么 $event
其 ->action->id
都是 view
因此我斷定問題出在 URL, yii 沒有正確辨識出 http://192.168.4.126/news/163
去看看 config 中的 URLManager Rules
, 這里當時多余的把 老式的 url rules 放在這里,去掉試試
'rules' => [
#'<controller:\w+>/<id:\d+>' => '<controller>/view',
#'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
#'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
['class' => 'yii\rest\UrlRule', 'controller' => ['users', 'news']],
],
果然, 解決了問題