我的代码出了点问题,我想这是我的控制器
namespace frontend\modules\v1\controllers;
use frontend\modules\v1\models\BrandApi;
use yii\rest\ActiveController;
class BrandController extends ActiveController {
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'results',
];
public $modelClass = 'frontend\modules\v1\models\BrandApi';
public function behaviors() {
$behaviors[] = [
'class' => \yii\filters\ContentNegotiator::className(),
'formats' => [
'application/json' => \yii\web\Response::FORMAT_JSON,
],
];
// $behaviors['authenticator'] = [
// 'class' => \yii\filters\auth\HttpBearerAuth::className(),
// ];
// $behaviors['access'] = [
// 'class' => \yii\filters\AccessControl::className(),
// 'only' => ['list'],
// 'rules' => [
// [
// 'actions' => ['list'],
// 'allow' => true,
// 'roles' => ['@'],
// ],
// ],
// ];
$behaviors['verbs'] = [
'class' => \yii\filters\VerbFilter::className(),
'actions' => [
'list' => ['get'],
],
];
return $behaviors;
}
public function actionList() {
return ['success' => true, 'results' => BrandApi::find()->all()];
}
}
我将ationIndex更改为actionList,因为我没有获得“成功”结果
所以如果我输入了错误的链接,我会得到html而不是json的答案
这是我在API模块中的配置文件
<?php
return [
'components' => [
'formatters' => [
\yii\web\Response::FORMAT_JSON => [
'class' => 'yii\web\JsonResponseFormatter',
'prettyPrint' => true,
'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
],
],
// 'response' => [
// 'class' => 'yii\web\Response',
// 'on beforeSend' => function ($event) {
// $response = $event->sender;
// if ($response->data !== null && Yii::$app->request->get('suppress_response_code')) {
// $response->data = [
// 'success' => $response->isSuccessful,
// 'data' => $response->data,
// ];
// // $response->statusCode = 200;
// 'http_response' = $response->statusCode;
// }
// $response->data = [
// 'success' => $response->isSuccessful,
// 'data' => $response->data,
// ];
// // $response->statusCode = 200;
// 'http_response' = $response->statusCode;
// },
// ],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'class' => 'yii\rest\UrlRule',
'pluralize' => false,
'controller' => 'api/default',
],
],
],
];
我的模特
<?php
namespace frontend\modules\v1\models;
use common\models\Brand;
class BrandApi extends Brand {
public function fields() {
return ['title'];
}
}
我尝试添加在教程中找到但没有用的响应配置
起初我以为是访问行为,但事实并非如此!我使用访问行为来确保请求api的用户已连接