我正在尝试按照指南中的说明实现Yii2 RESTful Web Service 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模型都是共同/模型。
我使用以下内容进行尝试:
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>
我花了很多时间在这上面。我已经调整了设置,阅读文档,还有更多,但没有成功。如果有人能看到问题是什么请告诉我,谢谢!!
答案 0 :(得分:5)
您对多重类名的默认UrlRule
行为感到满意:根据常见的REST约定,它足够智能将名为country
的控制器转换为复数形式名为/countries
的路线。
尝试GET http://myfrontendapp.loc/countries
并且它很可能正常工作。这也适用于UrlRule创建的所有其他路由,例如GET /countries/12345
或者,如果您要禁用此行为,则可以将UrlRule的$pluralize
设置为false。有关详细信息,请查看http://www.yiiframework.com/doc-2.0/guide-rest-routing.html。
答案 1 :(得分:1)
根据运行您的应用程序时的yii2休息标准,您必须非常具体地使用您的URI,即当您运行国家/地区的应用程序时,因此在运行复数时,所以在运行时您应该以http://myfrontendapp.loc/countries运行。
但是,您仍然希望国家/地区仅在您的urlmanager类型main.php
下的'controller'=>['c','country']
中。如果你的问题仍然存在,那么你需要检查你的目录结构......它应该是yii dir
api,后端,api下的前端应该是配置,模块里面的模块--v1和里面的v1--控制器和模型。
等
这肯定会解决您的问题......
答案 2 :(得分:0)
试试这个:
在advanced/api/web/index.html
添加require(__DIR__ . '/../../common/config/bootstrap.php');
而不是require(__DIR__ . '/../../common/config/aliases.php');
在advanced/common/config/bootstrap.php
添加Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api');
确保您的GET请求正确无误。删除&#39; api / web&#39;来自reqesst line。只需使用v1 / country
答案 3 :(得分:0)
你放了吗
的.htaccess
在文件夹中,如果没有创建
的.htaccess
包含以下内容
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
或者您可以使用以下网址检查请求,因为您使用的是高级模板
curl -i -H "Accept:application/json" "http://myfrontendapp.loc/frontend/web/index.php?r=countries"
在声明命名空间时,还有一件事要记住文件夹名称也区分大小写,因此请检查文件夹名称。