Laravel - 使用外部请求时POST数据为空

时间:2013-03-28 01:24:05

标签: php laravel

我是laravel的新手,我正在尝试实现一个简单的休息api。

我实施了控制器,并通过单元测试进行了测试。

我的问题在于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('menu@index');

我做错了什么?

更新

这真让我疯狂

我已经实现了一个新的laravel项目并且只有这个代码:

路线

Route::get('test', 'home@index');
Route::post('test', 'home@index');

控制器:

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电话:

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

响应:

{"test":[]}

任何人都可以指出我的错误。

这实际上阻止了我使用laravel,我真的很喜欢这个概念。

3 个答案:

答案 0 :(得分: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', 'home@index');

而不是

Route::get('test', 'home@index');
Route::post('test', 'home@index');

答案 1 :(得分:2)

如果您使用:Route::post('test', 'XYZController@test');
发送数据格式: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')并且它有效。

答案 2 :(得分:0)

删除标题 Content-type:application / json 如果您将其作为键值对而非json

发送
相关问题