gpt4 book ai didi

rest - 如何为Yii2-basic-template创建REST API

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

我想为yii2基本模板创建REST API。我遵循以下link

我创建了一个名为users的表,一个名为UserController的 Controller

<?php
namespace app\controllers;

use yii\rest\ActiveController;

class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
?>

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

'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '4534',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],

我的文件名为restapi,所以我尝试了这个URL http://localhost/~user/restapi/web/
我得到的只是一个404页面未找到错误。任何帮助,将不胜感激

最佳答案

使用这些配置:

'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],

您的资源应在这些url中可用:
http://localhost/~user/restapi/web/users http://localhost/~user/restapi/web/users/1
  • 注:除非您将yii\rest\UrlRule::$pluralize属性配置为不这样做,否则Yii会自动将用于端点的 Controller 名称进行复数。


  • 另外,如果使用 apache 服务器,则还需要在启用Pretty Urls之前通过将包含此内容的 .htaccess文件添加到 web文件夹中来配置服务器(请使用下面的链接(如果使用nginx):

    # 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>

    您提供的链接的文档中未描述此部分,因为您希望确实遵循了“安装和服务器配置”部分:

    http://www.yiiframework.com/doc-2.0/guide-start-installation.html#configuring-web-servers

    关于rest - 如何为Yii2-basic-template创建REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32626212/

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