Yii 2.0 restful 路由 404 问题

Yii 2.0 restful routing 404 issue

我正在尝试按照此处找到的 Yii2.0 示例使用我的简单产品 table 而不是用户。

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

我使用的是基本包,不是高级包。

当我尝试访问 localhost/product 我收到 404 错误。

当我使用 localhost/index.php 或 localhost/index.php/gii 我得到了预期的结果(默认主页和 gii 工具)。

这是我正在使用的东西。

配置文件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;

模特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',
        ];
    }
}

控制器ProductController.php

use yii\rest\ActiveController;

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

我曾尝试关闭 'enableStrictParsing' 并将 $pluralize 设置为 false,但没有成功。

我也尝试添加这个 .htaccess 文件,它给了我 500 而不是 404。

RewriteEngine on

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

我确定我在这里做了一些愚蠢的事情,但任何愿意指出这一点的人都会有很大的帮助。

谢谢!

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

扇贝船 - 我遇到了同样的问题。我在Yii2论坛上提出,得到了答案。您应该使用的 url 是 http://localhost/basic/web/index.php/products.

我还被建议将 'showScriptName' 更改为 true。建议是否则链接将无法正常生成。

还建议我可以编写一些重写规则以使用清洁器 url。

扇贝船。您可以在尚未解决问题时尝试这种方式。 如果您使用 Apache 作为 Web 服务器,您应该

  • 编辑 Apache 配置文件 httpd.conf 并找到像这样的块 <Directory>****</Directory><Directory "your web root dir">****</Directory>,修改AllowOverride NoneAllowOverride All
  • 取消注释 #LoadModule rewrite_module modules/ApacheModuleRewrite.dll
  • .hataccess 文件放在 index.php
  • 的基本目录中

@scallopboat - 我也有类似的问题。我收到了 view 操作的 404 响应。

按照

的说明解决

How to configure urlManager to use rest api with string id

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

使用以下 url 访问了 view 操作:

<a href="http://localhost/icdp-service/region/[mongo-id]" rel="nofollow noreferrer">http://localhost/icdp-service/region/[mongo-id]</a>

希望这对您有所帮助。