2017-09-16 110 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