drodsh7940
2015-01-30 15:49 阅读 45
已采纳

CakePHP路由器无法解析POST方法

I'm developing a CakePHP plugin which will be a Rest API kit and POST routes are not being parsed.

Routing

The problem is: Router::connect is not parsing any action with a different method than GET.

I would like to apply the common Rest routes like:

GET      /api/products       Get all products
GET      /api/products/:id   Get a single product
POST     /api/products       Create a product
PUT      /api/products/:id   Update a product
DELETE   /api/products/:id   Delete a product

I wouldn't like to use Router::mapResource to do that so I tried this:

// app/Config/core.php
Configure::write('Routing.prefixes', array('api')); 

// app/Config/bootstrap.php
CakePlugin::load('MY_PLUGIN', array('routes' => true));

// app/Config/routes.php
Router::parseExtensions('json');

// app/Plugin/MY_PLUGIN/Config/routes.php

Router::connect(
    '/api/:controller',
    array(
        'prefix' => 'api',
        'api' => true,
        'action' => 'index',
        'method' => 'GET',
    )
);

Router::connect(
    '/api/:controller/:id',
    array(
        'prefix' => 'api',
        'api' => true,
        'action' => 'view',
        'method' => 'GET',
    )
);

Router::connect(
    '/api/:controller',
    array(
        'prefix' => 'api',
        'api' => true,
        'action' => 'add',
        'method' => 'POST',
    )
);

I created a simple controller just to test it:

// app/Controller/ProductsController.php
public function api_index() {
    die('api_index');
}

public function api_view($id = null) {
    die('api_view');
}

public function api_add() {
    die('api_add');
}

Here's a list of responses that I get:

GET   /api/products      "api_index"
GET   /api/products/:id  "api_view"
POST  /api/products      "api_index"

Notice that the POST action couldn't find a proper route that match it. Anyone can explain it to me and knows a good solution for that?

Here's a list of questions that I already tried:

  1. CakePHP restful routes
  2. CakePHP REST route does not work
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

相关推荐