yii2 RESTful API 405 Method Not Allowed
2024-09-28 02:20:23
关于 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']],
],
果然, 解决了问题
最新文章
- 端盘子的服务生到月薪一万五的IT精英,你能相信吗
- Checkpoints codeforces 709B
- string函数分析
- 使用spring+mybatis+atomikos+tomcat构建分布式事务
- 杭电2059(dp)
- hdu 1010 Tempter of the Bone 深搜+剪枝
- keepavlied一些参数
- React 精要面试题讲解(五) 高阶组件真解
- 组装一台PRUSA I3打印机
- Spring 使用介绍(八)—— 零配置(一)
- redis设置过期时间
- Cobbler安装CentOS7系统时报错 What do you want do now?
- php有效防止同一用户多次登录
- IDEA开发常用快捷键
- HDU 1950 Bridging signals(LIS)
- 获取img元素图片的实际尺寸
- Python学习笔记18:标准库之多进程(multiprocessing包)
- vue1.0生命周期
- Ubuntu 18.04 如何固定图标到任务栏
- Firefox浏览器中,input输入框输入的内容在刷新网页后为何还在?