gpt4 book ai didi

rest - 如何解决这个 Yii2 RESTful Web 服务 API 路由错误?

转载 作者:行者123 更新时间:2023-12-02 08:31:02 25 4
gpt4 key购买 nike

我正在尝试按照指南中的描述实现 Yii2 RESTful Web 服务 API。我正在尝试使用高级应用程序模板。问题很简单,当我尝试访问该服务时,我得到的只是 404 错误。我想开始尝试一些简单的事情,所以我只是想使用国家表和关联的 ActiveRecord 类来尝试一下,这是代码:

这是在 frontend/config/main.php 的组件配置中:

    'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'country'],
],
],
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]

这是 frontend/controllers/CountryController.php 中的代码:

namespace frontend\controllers;

use yii\rest\ActiveController;

class CountryController extends ActiveController
{
public $modelClass = 'common\models\Country';
}

我所有的 ActiveRecord 模型,例如 country,都在 common/models 中。

我使用了以下方法来尝试:

curl -i -H "Accept:application/json" "http://myfrontendapp.loc/country"

这是我得到的输出:

HTTP/1.1 404 Not Found
Date: Fri, 31 Oct 2014 22:46:50 GMT
Server: Apache
Content-Length: 205
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /country was not found on this server.</p>
</body></html>

我在这上面花了很多时间。我已经调整了设置,阅读了文档等等,但都没有成功。如果有人能看到问题出在哪里,请告诉我,谢谢!!

最佳答案

您被类名复数的默认 UrlRule 行为击中了:根据常见的 REST 约定,它足够聪明,可以将名为 country 的 Controller 转换为复数名为 /countries 的路线。

尝试GET http://myfrontendapp.loc/countries,它很可能会正常工作。这也适用于 UrlRule 创建的所有其他路由,例如GET/countries/12345

或者,如果您想禁用此行为,您可以将 UrlRule 的 $pluralize 设置为 false。检查http://www.yiiframework.com/doc-2.0/guide-rest-routing.html了解更多信息。

关于rest - 如何解决这个 Yii2 RESTful Web 服务 API 路由错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26741156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com