Yii2 REST API URL Token配置问题:单条资源接口404错误求助
Yii2 REST API 单资源端点404错误修复方案
问题描述
搭建Yii2 REST API后,列表端点http://localhost/v1/countries可正常响应,但访问单资源端点http://localhost/v1/countries/AU时返回404错误,怀疑是URL Token配置问题。
相关代码
控制器代码(api/modules/v1/controllers/CountryController.php)
<?php namespace api\modules\v1\controllers; class CountryController extends \yii\rest\ActiveController { public $modelClass = 'api\modules\v1\models\Country'; }
模型代码(api/modules/v1/models/Country.php)
<?php namespace api\modules\v1\models; /** * This is the model class for table "country". * * @property string $code * @property string $name * @property int $population */ class Country extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'country'; } public static function primaryKey() { return ['code']; } /** * {@inheritdoc} */ public function rules() { return [ [['code', 'name'], 'required'], [['population'], 'integer'], [['code'], 'string', 'max' => 2], [['name'], 'string', 'max' => 52], [['code'], 'unique'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'code' => 'Code', 'name' => 'Name', 'population' => 'Population', ]; } }
URL配置(config/web.php 或 config/main.php)
'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'enableStrictParsing' => true, 'rules' => [ ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/default', 'v1/country'], 'tokens' => [ '{id}' => 'id:\\w+' ], //'pluralize'=>false, 'extraPatterns' => [ 'GET,POST,PUT index' => 'index', ], ], ], ],
端点测试情况
GET /countries:正常工作HEAD /countries:返回200状态码,响应为空POST /countries:正常工作GET /countries/AU:404错误HEAD /countries/AU:404错误PATCH /countries/AU:404错误PUT /countries/AU:404错误DELETE /countries/AU:404错误OPTIONS /countries:返回200状态码(响应为null)OPTIONS /countries/AU:404错误
修复步骤
1. 修正URL Token正则
原配置中'tokens' => [ '{id}' => 'id:\\w+' ]存在错误,该正则会匹配id:AU格式的字符串,而非直接匹配AU。需改为匹配国家代码的正则:
'tokens' => [ '{id}' => '[A-Z]{2}' ] // 匹配两位大写字母的国家代码,更精准 // 或通用匹配:'{id}' => '[\\w\\-]+'
2. 移除冲突的extraPatterns配置
原extraPatterns中的'GET,POST,PUT index' => 'index'会覆盖REST默认的单资源路由规则,导致无法识别/countries/AU这类路径,直接删除该配置项即可。
修改后的最终URL配置
'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'enableStrictParsing' => true, 'rules' => [ ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/default', 'v1/country'], 'tokens' => [ '{id}' => '[A-Z]{2}' ] ], ], ],
额外验证
确认模型已正确重写primaryKey()方法返回['code'],这部分代码已正确实现,无需修改。
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

