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 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)