为什么 RESTfull API 请求在 Yii2 中查看返回 404? [英] Why RESTfull API request to view return 404 in Yii2?

查看:207
本文介绍了为什么 RESTfull API 请求在 Yii2 中查看返回 404?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I adjusted module api, and created controller UserController extends ActiveController. All work fine, but view return 404 error.

  • http://example.com/api/user/45 – return 404 (Error)
  • http://example.com/api/user/view/?id=45 - return 200 (Ok)

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

Why yii\rest\UrlRule don't work in this case?

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

Info from official page about this rule:

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

答案:

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

推荐答案

1- 确保具有与相关 文档:

1- Be sure to have the same configs as shown in related docs:

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

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

2- Enabling Pretty Url in Yii requires further configurations at server level. For example if server is apache a similar configs to those should be added to htaccess file:

# 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 的更多细节和相关配置可以在 入门部分.还可以查看基本高级模板的教程:

More details and related configs to nginx can be found in the getting started section. Also check those tutorials for basic and advanced templates:

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

3- Depending on the project structure there is cases where you'll need to use RewriteBase or equivalent to define the base path holding your app. Like adding this to an apache's htaccess file:

RewriteBase /backend/api

4- 来自 rest 快速入门指南:

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

Yii will automatically pluralize controller names for use in endpoints. You can configure this using the yii\rest\UrlRule::$pluralize property.

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

Which means endpoint url is expected to look like http://example.com/api/users/45 by default.

这篇关于为什么 RESTfull API 请求在 Yii2 中查看返回 404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆