为什么简单的API控制器中不允许使用DELETE方法

时间:2019-02-04 01:52:21

标签: rest api yii2

基本工作正常:

  • 获取索引(/ api / v1 / pools)
  • 获取视图(/ api / v1 / pools / 1)
  • POST创建(/ api / v1 / pools)

但是当我尝试使用DELETE delete(/ api / v1 / pools / 1)时,出现以下消息:

  

不允许使用方法

     

URL不允许使用所请求的方法DELETE   / api / v1 / pools / 1。

我什至将checkAccess()定义为一个空方法,但似乎无济于事。

设置

控制器:

class PoolController extends \yii\rest\ActiveController
{
    public $modelClass = 'api\models\Pool';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        // authenticate by using an access token passed in the username authentication header
        $behaviors['authenticator'] = [
            'class' => HttpBasicAuth::className(),
        ];
        return $behaviors;
    }
}

配置:

....
'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    //'enableStrictParsing' => true,
    'rules' => [
    [
        'class' => 'yii\rest\UrlRule', 
        'controller' => ['v1/pool'],
    ],
]
....

请求和响应

cURL删除请求

curl -X DELETE \
  https://###/api/v1/pools/1 \
  -H 'Authorization: Basic dHBDMEUxNWVscl8tNlF6OFVYSGV5V0NydVBwdEp5elM6' \
  -H 'Content-Type: application/json' \
  -H 'cache-control: no-cache'

cURL响应

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>405 Method Not Allowed</title>
</head><body>
<h1>Method Not Allowed</h1>
<p>The requested method DELETE is not allowed for the URL         
/api/v1/pools/1.</p>
</body></html>

wget DELETE请求

wget --method DELETE 
  --header 'Content-Type: application/json'   
  --header 'Authorization: Basic dHBDMEUxNWVscl8tNlF6OFVYSGV5V0NydVBwdEp5elM6'   
  --header 'cache-control: no-cache'
  --output-document   - https://###/api/v1/pools/1

wget DELETE响应

HTTP request sent, awaiting response... 405 Method Not Allowed
2019-02-04 10:25:54 ERROR 405: Method Not Allowed.

为清楚起见,在同一控制器中另一个动作(视图)的工作请求/响应下方显示:

cURL GET请求

curl -X GET \
  https://###/api/v1/pools/1 \
  -H 'Authorization: Basic dHBDMEUxNWVscl8tNlF6OFVYSGV5V0NydVBwdEp5elM6' \
  -H 'cache-control: no-cache'

cURL GET响应

{"success":true,"data":{
    "id":1,
    "user_id":1,
    "name":"pool",
    ....
    "created_at":"2019-01-31 20:00:00"
}}

进一步摆弄之后,我发现它将始终返回此消息,即使我故意在控制器或api main配置中引起内部错误。这些工作动作确实表明发生内部错误。该请求甚至没有显示在调试器中,只有GET,POST和HEAD达到了要求。

1 个答案:

答案 0 :(得分:0)

经过很多浪费的时间,我发现请求甚至没有出现在api调试器(/ api / debug / default / view)中,并且该消息的回购中的grep没有返回任何内容。直到那时我才开始期待服务器。

服务器正在运行Apache / 2.4.35(Unix),在/etc/httpd/conf/httpd/extra/httpd-directories.conf中,有一条规则将阻止GET,HEAD和POST请求。我添加了PUT,PATCH,DELETE和OPTIONS。

<Directory /home>
    AllowOverride All
    Options -MultiViews -Indexes +FollowSymLinks +IncludesNoExec +Includes
    AllowMethods GET HEAD POST PUT PATCH DELETE OPTIONS
</Directory>

最后使它起作用。