簡體   English   中英

Yii2:REST POST請求參數未到達操作

[英]Yii2: REST POST request parameters not arriving to action

我正在使用Yii2制作REST API。
via /config/web.php啟用了漂亮的URL

'urlManager' => [
        'enablePrettyUrl' => true,
        //'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => $routes,
]  

這是$ routes變量的內容(基本上只是我的規則與web.php配置文件分開的php腳本的內容):

return [
        '<controller:[\w\-]+>/<id:\d+>' => '<controller>/view',
        '<controller:[\w\-]+>/<action:[\w\-]+>/<id:\d+>' => '<controller>/<action>',
        '<controller:[\w\-]+>/<action:[\w\-]+>' => '<controller>/<action>',
        'api/<controller:[\w\-]+>/<action:[\w\-]+>/<id:\d+>' => 'api/<controller>/<action>',
        'api/<controller:[\w\-]+>/<action:[\w\-]+>' => 'api/<controller>/<action>',
        'module/<module:[\w\-]+>/<controller:[\w\-]+>/<action:[\w\-]+>' => '<module>/<controller>/<action>',
        ['class' => 'yii\rest\UrlRule',
         'controller' => [
            'api/x_controller',
            'api/y_controller',
            'api/z_controller'
            ],
         'pluralize' => false,
        ]
];

並且它工作正常,除了我無法獲取我發送的任何參數(我的目標是JSON,但也嘗試發送application/x-www-form-urlencoded數據並具有相同的結果)。
嘗試從請求中獲取任何類型參數的當前代碼是:

public function actionDoSomething  
{
    $contentType = Yii::$app->request->getContentType();
    $raw = Yii::$app->request->getRawBody();
    $queryParams = Yii::$app->request->getQueryParams();
    $bodyParams = Yii::$app->request->getBodyParams();
    $token = Yii::$app->request->getBodyParam('access_token');
    $userID = Yii::$app->request->getBodyParam('user_id');
    $rawJson = file_get_contents("php://input");
}

不幸的是,所有這些變量都是null或為空,即使我的POST請求發送{"access_token":"XXXtoken","userId":"60"}

我猜它是關於我的urlManager的東西,但我不知道它是什么。

似乎問題根本不在Yii2中。
檢查我們的GoDaddy配置后,我們發現我們的A Record指向了錯誤的IP。
在將其指向正確的IP后,問題得以解決。

說實話,我不希望請求到達服務器,因為配置的那部分是錯誤的。

在過去,我在中間件位置使用類似的東西來一次解析各種類型的輸入。

//Store the various HTTP methods to check against
$methods_to_check = array('POST', 'PUT');    

//Check if this request should be parsed
if(in_array(strtoupper(Yii::$app->request->getMethod()), $methods_to_check)){
    //Initialize the value to store data in
    $input = '';

    //Get reference to PHP's input
    $file_handle = fopen('php://input', 'r');

    //Loop through PHP's input until end of stream is reached
    while(!feof($file_handle)){
        $s = fread($file_handle, 64);

        $input .= $s;
    }

    //Close reference to PHP's input
    fclose($file_handle);

    //Check if any data was passed, and merge the JSON-decoded version of it into the $_POST array
    if(!empty($input)) $_POST = array_merge($_POST, (array)json_decode($input));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM