【问题标题】:Settings url for REST api in Yii2Yii2 中 REST api 的设置 url
【发布时间】:2019-03-12 13:13:44
【问题描述】:

我正在尝试为 Restaps 配置 URL

在 web.php 中

'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => 'company',
        'extraPatterns' => [
            'POST' => 'create', // 'xxxxx' refers to 'actionXxxxx'
            'PUT {id}' => 'update',
            'PATCH {id}' => 'update',
            'DELETE {id}' => 'delete',
            'GET {id}' => 'view',
            'GET ' => 'index',
        ],
    ],
],

在 CompanyControler 中:

public $modelClass='app\models\Company';

/* Declare actions supported by APIs (Added in api/modules/v1/components/controller.php too) */
public function actions(){
    $actions = parent::actions();
    unset($actions['create']);
    unset($actions['update']);
    unset($actions['delete']);
    unset($actions['view']);
    unset($actions['index']);
    return $actions;
}

/* Declare methods supported by APIs */
protected function verbs(){
    return [
        'create' => ['POST'],
        'update' => ['PUT', 'PATCH','POST'],
        'delete' => ['DELETE'],
        'view' => ['GET'],
        'index'=>['GET'],
    ];
}
/**
 * {@inheritdoc}
 */
public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['logout'],
            'rules' => [
                [
                    'actions' => ['logout'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'logout' => ['post'],
            ],
        ],
    ];
}

public function actionIndex()
{
  // it work
}

public function actionView($id){
    $items = Company::find()->where(['id',$id])->one();
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return $items;
}

当我得到:/company 时,我得到了来自actionIndex 的答案,但是当我尝试得到company/10(其中 10 是项目 ID)时,我得到了错误 404。

如何正确设置网址管理器?

【问题讨论】:

    标签: php yii2 yii2-basic-app


    【解决方案1】:

    问题可能不在于 URL 管理器设置,而在于您的 view 操作。你应该替换:

    $items = Company::find()->where(['id',$id])->one();
    

    $items = Company::find()->where(['id' => $id])->one();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2016-07-17
      • 1970-01-01
      • 2021-08-13
      相关资源
      最近更新 更多