【问题标题】:Why RESTfull API request to view return 404 in Yii2?为什么 RESTful API 请求在 Yii2 中查看返回 404?
【发布时间】:2016-12-13 13:14:45
【问题描述】:

我调整了模块 api,并创建了控制器 UserController 扩展了 ActiveController。一切正常,但查看返回 404 错误。

为什么 yii\rest\UrlRule 在这种情况下不起作用?

来自官方页面的关于此规则的信息:

GET /users/123: return the details of the user 123;

回答

  1. 将 yii\rest\UrlRule::$pluralize 属性设置为 false;
  2. 将 enableStrictParsing 设置为 false。

【问题讨论】:

  • 附上实现UserController 的实际代码可能会有所帮助,并且可能会更详细地描述您的配置。

标签: php rest yii yii2


【解决方案1】:

1- 确保具有与相关docs 中所示相同的配置:

'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
    ],
]

2- 在 Yii 中启用 Pretty Url 需要在服务器级别进行进一步配置。例如,如果服务器是 apache,则应将类似的配置添加到 htaccess 文件中:

# Set document root to be "basic/web"
DocumentRoot "path/to/basic/web"

<Directory "path/to/basic/web">
    # use mod_rewrite for pretty URL support
    RewriteEngine on
    # If a directory or a file exists, use the request directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # Otherwise forward the request to index.php
    RewriteRule . index.php

    # ...other settings...
</Directory>

nginx 的更多细节和相关配置可以在getting started section 中找到。还可以查看 basicadvanced 模板的教程:

3- 根据项目结构,在某些情况下您需要使用 RewriteBase 或等效项来定义保存应用程序的基本路径。就像将此添加到 apachehtaccess 文件中:

RewriteBase /backend/api

4- 来自rest quick start guide

Yii 将自动复数控制器名称以用于端点。您可以使用 yii\rest\UrlRule::$pluralize 属性。

这意味着默认情况下,端点 url 应该看起来像 http://example.com/api/users/45

【讨论】:

  • 没关系。而且规则 ['class' => 'yii\rest\UrlRule', 'controller' => 'user'] 也有。
  • 谢谢,它帮助了我。但是我也设置了 enableStrictParsing = false。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
  • 2016-03-21
相关资源
最近更新 更多