用于返回 json 响应的 cakephp 控制器出错


Having error with the cakephp controller for returning json response

我准备了一个控制器,如下所示。

class TasksController extends AppController
{    
    public function index()
    {
        $this->paginate = [
            'contain' => ['Users'],
            'conditions' => [
                'Tasks.user_id' => $this->Auth->user('id'),
            ]
        ];
        $tasks = $this->paginate($this->Tasks);
        $this->set(compact('tasks'));
        //$this->set('tasks', $this->paginate($this->Tasks));
        $this->set('_serialize', ['tasks']);
    }
}

和我的应用程序控制器如下。

class AppController extends Controller
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent("Auth", [
            'authorize' => 'Controller',
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'unauthorizedRedirect' => $this->referer()
        ]);
        $this->Auth->allow(['display']);
    }
}

当我输入以下 URL "http://localhost/cake/tasks.json"时,我收到以下错误。

Error: Tasks.jsonController could not be found.
Error: Create the class Tasks.jsonController below in file: src/Controller/Tasks.jsonController.php

<?php
namespace App'Controller;
use App'Controller'AppController;
class Tasks.jsonController extends AppController
{
}

这里有什么问题以及如何在不添加路由或 json 视图文件的情况下解决它。[我正在使用 CakePHP 3.0]

看起来你还没有让 Cake 知道期待.json文件扩展名。结果蛋糕正在寻找Tasks.jsonController。您想将其添加到您的配置/路由.php文件中:-

Router::extensions(['json']);
有关

更多详细信息,请参阅有关路由文件扩展名的文档。