使用cakePHP 3.5创建没有视图的Rest API

问题描述 投票:1回答:3

我正在尝试创建没有视图的Rest API,并计划在angular 2应用程序中使用这些api。对此有任何想法吗?

cakephp cakephp-3.x cakephp-3.1 cakephp-3.4 cakephp-3.3
3个回答
1
投票

蛋糕使这非常容易。我学到的一些东西没有观点。

设置_serialize变量

$data = ['cheeses' => ['gouda', 'pepper jack', 'cheddar']];
$this->set('responseData', $data);
$this->set('_serialize', 'responseData');

抛出错误的请求异常和其他与网络相关的异常

Cake将为您呈现漂亮的json视图。

在发出时设置接受标头,并将ajax请求设置为application / json

您可以为api版本使用蛋糕前缀

看看Stateless Authentication你的api


0
投票

在你的AppController.php中,使用这些参数,所有控制器都将在json中呈现

public function beforeRender(Event $event)
{
     $this->RequestHandler->renderAs($this, 'json');
     $this->response->type('application/json');
     $this->set('_serialize', true);
}

0
投票

CakePHP将轻松渲染json。

在你的控制器中,看起来像什么。

protected   $responseBody   =   [];

public function beforeRender(Event $event){

    foreach($this->responseBody as $responseKey=>$response){

       $this->set($responseKey, $response);
    }
    $this->set('_serialize', array_keys($this->responseBody));
}

public function initialize()
{
    parent::initialize();

    $this->RequestHandler->renderAs($this, 'json');
}

public function index(){

    $this->request->allowMethod(['get']);  // Method like post,get..

    $this->responseBody["statusCode"]       =   200;

    $this->responseBody["statusDescription"]        =   ''; //You send any text in json.

    $this->responseBody["data"]  =  []; // All data that you can send.

}

有关更多信息,您可以查看CakePHP Cookbook REST API以单击here

© www.soinside.com 2019 - 2024. All rights reserved.