简体   繁体   中英

Yii 2.0 restful routing 404 issue

I am trying to follow the Yii2.0 example as found here with my simple product table instead of User.

http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html

I'm using the basic package, not advanced.

When I try to access localhost/product I get a 404 error.

When I use localhost/index.php or localhost/index.php/gii I get the expected result (the default homepage, and the gii tool).

Here is what I'm working with.

The config file web.php

$params = require(__DIR__ . '/params.php');

$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [

    'request' => [
        // !!! insert a secret key in the following (if it is empty) - this is required     by cookie validation
        'cookieValidationKey' => 'xxx',
        'parsers' => [
            'application/json' => 'yii\web\JsonParser',
        ],
    ],
    'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => [
            ['class' => 'yii\rest\UrlRule', 'controller' => 'product'],
        ],
    ],
    'cache' => [
        'class' => 'yii\caching\FileCache',
    ],
    'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => true,
    ],
    'errorHandler' => [
        'errorAction' => 'site/error',
    ],
    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        // send all mails to a file by default. You have to set
        // 'useFileTransport' to false and configure a transport
        // for the mailer to send real emails.
        'useFileTransport' => true,
    ],
    'log' => [
        'traceLevel' => YII_DEBUG ? 3 : 0,
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
                'levels' => ['error', 'warning'],
            ],
        ],
    ],
    'db' => require(__DIR__ . '/db.php'),
],
'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';

    config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module';
}

return $config;

The Model Product.php

    namespace app\models;

use yii\db\ActiveRecord;

/**
 * This is the model class for table "product".
 *
 * @property integer $ProductID
 * @property string $Name
 * @property double $Price
 * @property string $ShortDesc
 * @property string $LongDesc
 * @property string $PicUrl
 */
class Product extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'product';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Price'], 'number'],
            [['ShortDesc', 'LongDesc', 'PicUrl'], 'string'],
            [['Name'], 'string', 'max' => 60]
        ];
    }

    /**
     * @inheritdoc
     */
    public static function primaryKey()
    {
        return ['ProductID'];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ProductID' => 'Product ID',
            'Name' => 'Name',
            'Price' => 'Price',
            'ShortDesc' => 'Short Desc',
            'LongDesc' => 'Long Desc',
            'PicUrl' => 'Pic Url',
        ];
    }
}

The controller ProductController.php

use yii\rest\ActiveController;

class ProductController extends ActiveController
{
    public $modelClass = 'app\models\Product';
}

I have tried to turn off 'enableStrictParsing' and set $pluralize to false, with no luck.

I have also tried adding this .htaccess file which gave me a 500 rather than a 404.

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

I'm sure I've done something silly here, but anyone willing to point that out will be a huge help.

Thanks!

只需在urlManager数组中将enableStrictParsing设置为false

Scallopboat - I had the same issue. I raised it on the Yii2 forum and got the answer. The url you should use is http://localhost/basic/web/index.php/products .

I was also advised to change 'showScriptName' to true. The advise was that otherwise the links won't generate ok.

It was also suggested I could write some rewrite rules to use a cleaner url.

@scallopboat - I too have a similar problem. I got 404 response for view action.

Solved by following the instruction from,

How to configure urlManager to use rest api with string id

'rules' => [
            [
                'class' => 'yii\rest\UrlRule', 
                'controller' => 'region',
                'pluralize'=>false,
                'tokens' => [ '{id}' => '<id:\\w+>' ]
            ],
        ],

Accessed the view action using the below url:

http://localhost/icdp-service/region/[mongo-id]

Hope this helps.

Scallopboat. You can try this way while you do not solve your problem yet. If you are using Apache as your web server,you should

  • edit the Apache config file httpd.conf and find blocks like <Directory>****</Directory> and <Directory "your web root dir">****</Directory> ,modify the AllowOverride None to AllowOverride All
  • uncomment the #LoadModule rewrite_module modules/ApacheModuleRewrite.dll
  • place the .hataccess file in your the base directory of your index.php

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