在CakePHP中强制JSON响应

chr*_*ony 6 rest json cakephp

我创建了如下所示的路线:

Router::connect('/:api/:controller/:action/*', array(), array('api'=>'api'));
Router::connect('/:api/:controller', array('action' => 'index'), array('api'=>'api'));
Router::connect('/:api/', array('controller' => 'index', 'action' => 'index'), array('api'=>'api'));
Run Code Online (Sandbox Code Playgroud)

基本上,我希望通过特定端点发出的所有请求都以JSON响应.在上面的例子中,所有使用api前缀的请求.例如:

http://localhost/api/products
Run Code Online (Sandbox Code Playgroud)

应该返回JSON响应而不是HTML.请注意,即使没有定义.json扩展名,它也应该以这种方式工作.

Ale*_*len 8

所以我猜你的控制器中你是否设置了api前缀,如果是这样你序列化你给回到视图的数据?如果是,那么只需添加:

$this->RequestHandler->renderAs($this, 'json');
Run Code Online (Sandbox Code Playgroud)