2017-09-16 102 views
1

我试图在没有视图的情况下创建Rest API并计划在角度2应用程序中使用这些API。对此有什么想法?使用cakePHP创建Rest API无视图3.5

+2

开始阅读说明书? https://book.cakephp.org/3.0/en/development/rest.html – burzum

回答

0

蛋糕使这非常容易。我学到了一些没有意见的东西。

设置_serialize变量

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

掷坏请求异常和其他网络相关的异常

蛋糕将呈现漂亮的JSON意见你。

发行和Ajax请求时,设置您接受头是application/JSON

您可以在Stateless Authentication使用蛋糕前缀API版本

查找您的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的食谱REST API点击here