与cakephp控制器有错误返回json响应

时间:2016-03-02 14:18:04

标签: php json cakephp

我准备了如下控制器。

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']);
    }
}

和我的AppController如下。

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']);
    }
}

当我输入以下网址时," 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]

1 个答案:

答案 0 :(得分:2)

看起来你没有让Cake知道期望.json文件扩展名。结果,Cake正在寻找Tasks.jsonController。您想在config / routes.php文件中添加它: -

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

有关详细信息,请参阅routing file extensions上的文档。