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

果然, 解决了问题

最新文章

  1. 端盘子的服务生到月薪一万五的IT精英,你能相信吗
  2. Checkpoints codeforces 709B
  3. string函数分析
  4. 使用spring+mybatis+atomikos+tomcat构建分布式事务
  5. 杭电2059(dp)
  6. hdu 1010 Tempter of the Bone 深搜+剪枝
  7. keepavlied一些参数
  8. React 精要面试题讲解(五) 高阶组件真解
  9. 组装一台PRUSA I3打印机
  10. Spring 使用介绍(八)—— 零配置(一)
  11. redis设置过期时间
  12. Cobbler安装CentOS7系统时报错 What do you want do now?
  13. php有效防止同一用户多次登录
  14. IDEA开发常用快捷键
  15. HDU 1950 Bridging signals(LIS)
  16. 获取img元素图片的实际尺寸
  17. Python学习笔记18:标准库之多进程(multiprocessing包)
  18. vue1.0生命周期
  19. Ubuntu 18.04 如何固定图标到任务栏
  20. Firefox浏览器中,input输入框输入的内容在刷新网页后为何还在?

热门文章

  1. px、em、rem的区别
  2. RocketMQ通信协议
  3. JVM组成部分以及内存模型
  4. weblogic基本安装部署
  5. C中strstr的实现方法
  6. google,百度地图POI下载
  7. ajax请求接口数据
  8. 调整 firefox 源代码查看器的字体
  9. 《The Story of My Life》Introductiom - The Life and Work of Helen Keller
  10. C#开发Unity游戏教程循环遍历做出推断及Unity游戏演示样例