【问题标题】:Having error with the cakephp controller for returning json responsecakephp 控制器返回 json 响应时出错
【发布时间】:2016-03-02 14:18:04
【问题描述】:

我已经准备了一个控制器如下。

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

当我输入以下 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]

【问题讨论】:

  • 转到"http://localhost/cake/tasks会发生什么
  • 它在网络视图中显示任务列表。
  • 你定义了哪些路由器扩展?
  • 我没有定义任何路由器扩展。它应该自动化 json 扩展吧?

标签: php json cakephp


【解决方案1】:

您似乎没有让 Cake 知道需要 .json 文件扩展名。因此,Cake 正在寻找Tasks.jsonController。你想在你的 config/routes.php 文件中添加这个:-

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

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

【讨论】:

  • 我认为它会被设置为默认允许 json 响应。
猜你喜欢
  • 1970-01-01
  • 2013-09-20
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 2016-01-30
  • 1970-01-01
相关资源
最近更新 更多