2015-02-05 70 views
2

我有個笨REST API添加到HTTP響應時,使用這個庫創建: https://github.com/chriskacerguis/codeigniter-restserver怎樣的位置頭球笨其餘服務器

對於我的POST方法,一旦資源已成功創建,我想以包括位置標頭,其包括用於獲取新創建/更新的資源的URI。 我不清楚如何做到這一點。 有沒有人試過類似的東西?

到目前爲止,我只是將創建的細節添加到響應主體......但我最終希望將GET url添加爲位置標題。

這是我的邏輯看起來像至今:

public function widget_post() 
{ 
     $new_widget_data = array(
       'location' =>$this->post('location'), 
       'name' => $this->post('name'), 
       'cost' => $this->post('cost') 
       ); 

     // validate post data 
     if (!$this->isvalidpost($new_widget_data)) { 
       $this->response("Invalid data",400); 
     } 

     // add to database 
     $res = $this->widget_model->notify_servers($new_widget_data); 
     $new_widget_data['results']=$res; 
     if ($res) { 
       //append GET url to return value      
       $new_widget_data['GET']=base_url()."/index.php/widgets/widget/".$new_widget_data['name']; 
       $this->response($new_widget_data,201); //HTTP Created 201   
     } else { 
     $this->response("Unable to process request",500); //HTTP Internal server error 
     } 

任何建議,將不勝感激。謝謝。

回答

2

我不相信當前版本的庫提供了一種方法來執行此操作。

您擁有的一個選項是將php header()函數與REST_Controller類提供的response()函數結合使用。

header(「Location:location/to/new/resource」);

然後調用響應函數,確保您設置201代碼。 $ this-> response($ new_widget_data,201);

通常情況下,位置標題默認會觸發重定向,因此請確保始終設置201代碼。

http://php.net/manual/en/function.header.php

0

您是否嘗試過重定向('widgets?widget ='。$ new_widget_data ['name']); 或者我錯過了觀點?

+0

我不認爲你完全理解我的問題。我不想將請求重定向到新創建的小部件。相反,當我使用201 CREATED發送響應時,我想包含一個帶有URI的位置標題標記。這說明了嗎? – dot 2015-02-08 21:49:33