cakePHP 3.0 Action PagesController::myaction.json() could not be found, or is not accessible."

杀马特。学长 韩版系。学妹 提交于 2021-02-10 19:01:37

问题


I am migrating an existing 2.5 app over to 3.0. I am getting an 404 error when using ajax. This works fine in cakePHP 2.5

url: "/cakephp3/pages/myaction.json"

I don't see any step that I might have missed.

I am sure it is a routing issue with the .json extension

routes.php

Router::scope('/', function ($routes) {

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

    $routes->connect('/', ['controller' => 'Pages', 'action' => 'home']);
    $routes->connect('/hotel-training-courses', ['controller' => 'pages', 'action' => 'trainingCourses']);
    $routes->connect('/feature-tour', ['controller' => 'pages', 'action' => 'features']);
    $routes->connect('/contact-us', ['controller' => 'pages', 'action' => 'contact']);
    $routes->fallbacks('InflectedRoute');
});

PagesController.php

public function initialize()
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
}

public function myaction(){

    $this->request->onlyAllow('ajax');

    $userName = $this->request->data['name'];
    $userCompany = $this->request->data['company'];
    $userEmail = $this->request->data['email'];
    $userPhone = $this->request->data['phone'];

    //send an email

}

The previous app was able to detect the request type and return with the same type. There was no need to set the render.


回答1:


Global extensions must be defined outside of scopes

Router::extensions() must be placed outside of, and in case it should apply to all routes, invoked before defining any scopes and routes.

In case you want to restrict extension parsing to a specific scope, use RouteBuilder::extensions(), ie either

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

Router::scope('/', function (RouteBuilder $routes) {
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'home']);
    //...
});

or

Router::scope('/', function (RouteBuilder $routes) {
    $routes->extensions(['json', 'xml']);

    $routes->connect('/', ['controller' => 'Pages', 'action' => 'home']);
    //...
});

See Cookbook > Routing > Routing File Extensions

Request::onlyAllow() doesn't exist anymore

Request::onlyAllow() has been renamed to Request::allowMethod(), so that's the next problem that you'll encouter.

See

  • Cookbook > 3.0 Migration Guide > Network > Request
  • \Cake\Network\Request::allowMethod()

Enable debug mode

Also you should enable debug mode so that you receive meaningful error messages with the appropriate details, necessary to debug such problems.



来源:https://stackoverflow.com/questions/29687289/cakephp-3-0-action-pagescontrollermyaction-json-could-not-be-found-or-is-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!