最近在调试RESTful API示例时,出现以下错误:
{
"name": "Exception",
"message": "Class yii/web/JsonParser does not exist",
"code": -1,
"type": "ReflectionException",
"file": "/Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/di/Container.php",
"line": 426,
"stack-trace": [
"#0 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/di/Container.php(426): ReflectionClass->__construct('yii/web/JsonPar...')",
"#1 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/di/Container.php(364): yii\\di\\Container->getDependencies('yii/web/JsonPar...')",
"#2 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/di/Container.php(156): yii\\di\\Container->build('yii/web/JsonPar...', Array, Array)",
"#3 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/BaseYii.php(345): yii\\di\\Container->get('yii/web/JsonPar...', Array)",
"#4 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/web/Request.php(531): yii\\BaseYii::createObject('yii/web/JsonPar...')",
"#5 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/rest/CreateAction.php(51): yii\\web\\Request->getBodyParams()",
"#6 [internal function]: yii\\rest\\CreateAction->run()",
"#7 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/base/Action.php(94): call_user_func_array(Array, Array)",
"#8 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/base/Controller.php(157): yii\\base\\Action->runWithParams(Array)",
"#9 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/base/Module.php(528): yii\\base\\Controller->runAction('create', Array)",
"#10 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/web/Application.php(103): yii\\base\\Module->runAction('deptinfo/create', Array)",
"#11 /Users/Desktop/workspaces/php/yii2-ims/vendor/yiisoft/yii2/base/Application.php(386): yii\\web\\Application->handleRequest(Object(yii\\web\\Request))",
"#12 /Users/Desktop/workspaces/php/yii2-ims/api/web/index.php(10): yii\\base\\Application->run()",
"#13 {main}"
]
}
其实,这是自己给自己挖的一个坑,结果把自己给陷进去了,下面是配置文件的代码:
'request' => [
'class' => 'yii\web\Request',
'parsers' => [
'application/json' => 'yii/web/JsonParser',
],
],
问题就在于配置时将 “yii/web/JsonParser”写错了,正确的是 “yii\web\JsonParser”,命名空间应以反斜杠“\”分割,看似很小的问题,结果调试了很长时间才找到原因,所以在写代码配置的时候一定要认真仔细,以免被自己误导,浪费宝贵的时间。