我尝试通过引用Yii2 REST GUIDE创建REST API,但不幸的是我只有GET方法工作.
示例网址:
除了上面的URL,其他一切都给了我一个NOT FOUND(404)错误页面(甚至不是JSON响应).
应用\控制器\ EmployeeController.php
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class EmployeeController extends ActiveController
{
public $modelClass = 'app\models\Employee';
/**
* @return array
*/
protected function verbs()
{
return [
'index' => ['GET', 'HEAD'],
'view' => ['GET', 'HEAD'],
'create' => ['POST'],
'update' => ['PUT', 'PATCH'],
'delete' => ['DELETE'],
];
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序\型号\ Employee.php
<?php
namespace app\models;
use Yii;
class Employee extends \yii\db\ActiveRecord
{
public $primaryKey = 'emp_no';
/**
* @inheritdoc
*/
public static function tableName()
{
return 'employees';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['emp_no', 'birth_date', 'first_name', 'last_name', 'gender', 'hire_date'], 'required'],
[['emp_no'], 'integer'],
[['birth_date', 'hire_date'], 'safe'],
[['gender'], 'string'],
[['first_name'], 'string', 'max' => 14],
[['last_name'], 'string', 'max' => 16],
[['emp_no'], 'unique'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'emp_no' => 'Emp No',
'birth_date' => 'Birth Date',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'gender' => 'Gender',
'hire_date' => 'Hire Date',
];
}
Run Code Online (Sandbox Code Playgroud)
web.php配置
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'employer'],
],
],
Run Code Online (Sandbox Code Playgroud)
的.htaccess
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
Run Code Online (Sandbox Code Playgroud)
我希望我提供了所有相关信息来解决我的问题.提前致谢.:-)
你已经定义了控制器的名称,employer而它应该是employee我没有错,这不是在这里编写代码的拼写错误
更改为以下内容
['class' => 'yii\rest\UrlRule', 'controller' => 'employee'],
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |