drodsh7940 2015-01-30 15:49
浏览 51
已采纳

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条回答 默认 最新

  • dongwo5940 2015-01-30 17:22
    关注

    As the Documentation on http://book.cakephp.org/2.0/en/development/routing.html#using-additional-conditions-when-matching-routes points out, you should use [method] and not method.

    [method] Only match requests with specific HTTP verbs.

    Router::connect(
    '/api/:controller/*',
    array(
        'prefix' => 'api',
        'api' => true,
        'action' => 'add',
        '[method]' => 'POST',
    )
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题