zoukankan      html  css  js  c++  java
  • yii2 RESTful API 405 Method Not Allowed

    关于 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 的所在:

    yii2filtersVerbFilter.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
    estUrlRule', 'controller' => ['users', 'news']],
    			],
    

    果然, 解决了问题

    作者:ganiks
    出处:http://www.cnblogs.com/ganiks/
    本作品由 Ganiks 创作, 欢迎转载,但任何转载必须保留完整文章,在显要地方显示署名以及原文链接。如您有任何疑问,请给我留言。
  • 相关阅读:
    一些jquery常用方法
    如何判断js中的数据类型
    SDL结合QWidget的简单使用说明(2)
    C++引用详解
    SDL结合QWidget的简单使用说明
    Qt::浅谈信号槽连接,参数在多线程中的使用
    Qt::带返回值的信号发射方式
    Windows:子线程中创建窗口
    Qt:小项目仿QQ修改头像界面,技术点记录
    Qt::QWindow多窗口争抢置顶状态解决方案
  • 原文地址:https://www.cnblogs.com/ganiks/p/yii2-RESTful-API-405-Method-Not-Allowed.html
Copyright © 2011-2022 走看看