问题是Yii2中RESTful服务器的响应以XML形式返回,而我需要它们以JSON格式返回。
我遵循了Yii2指南,控制器看起来一样,在连接到数据库的模型方面有所不同(该模型先前是从高级模板中的默认模型复制的),web config也与指南相同。
为了澄清任何疑虑,这里是代码:
UserController.php
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
web.php($config)
$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' => 'WgkzlqvStTfGXY-ToFlQIJRDMX4LUQtY',
'parsers'=>[
'application/json'=>'yii\web\JsonParser'
]
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
],
'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,
];
我尝试在配置组件中进行设置:
response=>[
'format'=>yii\web\Response::FORMAT_JSON
]
...但它仍然响应XML。我该怎么做才能让它响应JSON?