简体   繁体   中英

Yii, invalid request on action's controller from a module

This is the first time i am building a module in Yii , this module is about an API where i can gather data from other servers and apps, i have created the module via GII and added the module into the config file, everything works fine for now.. I created a new controller inside this API module with action index as usual, still everything goes fine, but when i add another action to this controller and try to access it on the browser, i get the "Your request is invalid" message, i have tried with changing the name of the controller because i have another controller with the same name but outside the module, also tried changing the action name, but still no clue.

Controller:

<?php 
Class ItemsController extends Controller
{
    public function actionIndex()
    {
        $items = Items::model()->findAll();

        header('Content-Type: application/json');

        foreach($items as $item)
            echo json_encode($item->attributes);
    }

    public function loadModel($id)
    {
        $model = Items::model()->findByPk($id);

        if($model)
            return $model;
    }

    public function actionData($id)
    {
        $item = $this->loadModel($id);

        if($item)
        {
            header('Content-Type: application/json');

            echo json_encode($item);
        }

        else
        {
            throw new Exception("Data could not be found", 404);

        }
    }
}
?>

What is the problem on this script?

EDIT: the url is 127.0.0.1/APP/api/item/dat/2

It seems you are using urlManager which by default has no rule for modules. In your main.php config file, add the following line into your rules :

'<module:\w+>/<controller:\w+>/<action:\w+>'=>'<module>/<controller>/<action>',

And if you want to give ID add the following line too:

'<module:\w+>/<controller:\w+>/<action:\w+>/<id:\d+>'=>'<module>/<controller>/<action>',

In order to write your own customized rules (and also be more familiar), you may find Yii's official document about URL Management useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM