【问题标题】:YII2 Restfull strange behaviourYII2 Restfull 奇怪的行为
【发布时间】:2015-08-19 09:32:41
【问题描述】:

尝试使用 Yii2 Advanced 模板创建 API 应用程序(基于 RESTFull 服务)。为此目的创建了子域 api.domain.com。

目录结构如下:

问题是,当我尝试向 api.domain.com/users 发送 GET 请求时得到以下响应:

{
  "name": "Not Found",
  "message": "Page not found.",
  "code": 0,
  "status": 404,
  "type": "yii\web\NotFoundHttpException",
  "previous": {
    "name": "Invalid Route",
    "message": "Unable to resolve the request \"user/index\".",
    "code": 0,
    "type": "yii\base\InvalidRouteException"
  }
}

这里是配置文件:

https://gist.github.com/d1930b6bf20e3d50fe63

这是控制器(位于 Controllers 文件夹中):

https://gist.github.com/anonymous/180a7e791e879570e0f4

问题是……

我做错了什么?

【问题讨论】:

  • 你的 .htaccess 文件呢?您是否为干净的 url 支持设置了额外的服务器配置?
  • @SalemOuerdani nginx 文件已配置。而且它在正确的路线上。
  • 不确定出了什么问题,但是您可以尝试从components[request] 中删除components[response]\yii\web\Request 类并尝试它是否有效?您可以查看this file,我的 API 在这些配置中运行良好。
  • @SalemOuerdani 响应正常。该错误与响应无关
  • 试试这个 url 调用api.domain.com/index.php?r=users,它有效吗?在 .htacces 中,您可以隐藏 index.php 部分:stackoverflow.com/questions/26525320/enable-clean-url-in-yii2

标签: php rest get yii2 restful-architecture


【解决方案1】:

确保您已将 api 应用程序的路径添加到公用文件夹中的 bootstrap.php 中。它必须看起来像:

<?php
Yii::setAlias('common', dirname(__DIR__));
Yii::setAlias('frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('console', dirname(dirname(__DIR__)) . '/console');
Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api');                    <-- this line

顺便说一句,文件位于common/config/bootstrap.php

【讨论】:

  • 这为我解决了问题,但我的 bootstrap.php 略有不同 Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
【解决方案2】:

三件事:

  1. 检查复数形式。例如:“v1/post”应该是“v1/posts”
  2. 添加“动作”前缀。例如:“actionImport()”
  3. 烤肉串格式。例如:“v1/getSample”应该是“v1/get-sample”
  4. 如果需要,在 main.php:urlManager 中添加规则“extraPatterns”。例如:

    ['class' => 'yii\rest\UrlRule', 'controller' => 'v1/report', 'extraPatterns'=>['analytics' => 'analytics', '报告' => '报告']],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2015-07-20
    • 2010-10-03
    • 2021-07-12
    • 2013-10-04
    相关资源
    最近更新 更多