Why RESTfull API request to view return 404 in Yii2?

旧街凉风 提交于 2019-12-11 06:46:30

问题


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)

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;

ANSWER:

  1. Set yii\rest\UrlRule::$pluralize property to false;
  2. Set enableStrictParsing to 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- 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>

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

  • https://www.diggin-data.de/dd-cms/blog/post/view/id/1004/name/Creating+a+REST+API+for+Yii2-basic-template
  • http://budiirawan.com/setup-restful-api-yii2/

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- From the rest quick start guide:

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

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



来源:https://stackoverflow.com/questions/41122081/why-restfull-api-request-to-view-return-404-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!