2013-03-28 103 views
4

我是laravel的新手,我試圖實現一個簡單的休息api。Laravel - POST數據在使用外部請求時爲空

我有控制器實現,並通過單元測試進行測試。

我的問題是與POST請求。

通過測試輸入:json有數據,通過外部的休息客戶端它返回null。

這是單元測試

$newMenu = array(
     'name'=>'Christmas Menu', 
     'description'=>'Christmas Menu', 
     'img_url'=>'http://www.example.com', 
     'type_id'=>1, 
    ); 
    Request::setMethod('POST'); 
    Input::$json = $newMenu; 
    $response = Controller::call('[email protected]'); 

我在做什麼錯誤的代碼?

UPDATE:

這是真的快把我逼瘋了

我實例化一個新的laravel項目,只是有這樣的代碼:

路線

Route::get('test', '[email protected]'); 
Route::post('test', '[email protected]'); 

控制器:

class Home_Controller extends Base_Controller { 

    public $restful = true; 
    public function get_index() 
    { 
     return Response::json(['test'=>'hello world']); 
    } 
    public function post_index() 
    { 
     return Response::json(['test'=>Input::all()]); 
    } 
} 

捲曲電話:

curl -H "Accept:application/json" -H"Content-type: application/json" -X POST -d '{"title":"world"}' http://localhost/laravel-post/public/test 

響應:

{"test":[]} 

任何人都可以點我什麼是錯的。

這真的阻止我使用laravel,而且我非常喜歡這個概念。

+0

您是否嘗試過在瀏覽器?只是爲了確保你的捲髮電話不是問題? – 2013-03-28 17:20:41

+0

我嘗試了使用休息客戶端(CocoaRest客戶端),但我還沒有創建GUI,所以沒有瀏覽器測試 – 2013-03-28 22:56:43

回答

7

因爲您將JSON發佈爲您的HTTP正文,所以您不會收到Input :: all(); 你應該使用:

$postInput = file_get_contents('php://input'); 
$data = json_decode($postInput, true); 

$response = array('test' => $data); 
return Response::json($response); 

您也可以使用

Route::any('test', '[email protected]'); 

代替

Route::get('test', '[email protected]'); 
Route::post('test', '[email protected]'); 
2

如果你使用:Route::post('test', '[email protected]');
發送數據格式:Content-type : application/json
例如:{"data":"foo bar"}

,你可以得到的職位(任何人:得到,放...等)數據:

Input::get('data'); 

這顯然是寫在這裏:http://laravel.com/docs/requests 。正確Content-type非常重要!

我不確定您的CURL調用是否正確。也許這可能會有所幫助:How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?

我正在使用Input::get('data'),它的工作原理。

0

刪除頭內容類型:應用程序/ JSON如果要發送它作爲鍵值對,而不是一個JSON