我正在使用Yii2高级模板,我添加了一个新文件夹api
来处理api请求,我正在404 error
使用yii\base\InvalidRouteException
。
api\config\main.php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'rest-api',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableSession' => false,
],
'response' => [
'format' => yii\web\Response::FORMAT_JSON,
'charset' => 'UTF-8',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'request' => [
'class' => '\yii\web\Request',
'enableCookieValidation' => false,
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['v1/test']],
],
],
],
'params' => $params,
];
这是我的api\controllers\v1\TestController.php
namespace api\controllers\v1;
use yii\filters\auth\QueryParamAuth;
use yii\rest\ActiveController;
class TestController extends ActiveController
{
public $modelClass = 'common\models\User';
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => QueryParamAuth::className(),
];
return $behaviors;
}
public function actions() {
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionTest()
{
return "1111";
}
}
我想我正在做一些关于命名空间的事情。
答案 0 :(得分:2)
我认为你错过了v1模块。我也参与了其余的api
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/aliases.php')
);
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => '@app\modules\v1\controllers',
'modules' => [
'v1' => [
'basePath' => '@app/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'response' => [
'class' => 'yii\web\Response',
],
'urlManager' => [
'class' => 'yii\web\UrlManager',
'showScriptName' => false,
//'enableStrictParsing' => true,
'enablePrettyUrl' => true,
'rules' => [
//API V1
[
'class' => 'yii\rest\UrlRule',
'controller' => ['v1/country'],
'tokens' => [
'{id}' => '<id:\\w+>',
],
],
],
],
],
'params' => $params,
];
有关详细信息,请参阅此url