当使用外部请求时,POST数据为空


Laravel - POST data is null when using external request

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

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

我的问题是POST请求。

通过测试Input:json有数据,通过外部rest客户端返回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 -H "Accept:application/json" -H"Content-type: application/json" -X POST -d '{"title":"world"}' http://localhost/laravel-post/public/test

反应:

{"test":[]}

谁能告诉我哪里不对?

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

因为你是张贴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');

删除header Content-type: application/json如果你发送的是键值对而不是json

如果使用:Route::post('test', 'XYZController@test');
发送数据格式:Content-type : application/json
例如:{"data":"foo bar"}

您可以使用:

获取post(任何其他:get, put…等)数据:
Input::get('data');

这里写得很清楚:http://laravel.com/docs/requests. 正确,Content-type非常重要!

我不确定你的CURL调用是正确的。也许这可能是有帮助的:如何POST JSON数据与Curl从终端/命令行测试Spring REST?

我使用Input::get('data'),它的工作

我正面临这个问题,我的帖子的响应总是空的。为了解决这个问题,我把body键放在guzzle对象中,像这样

$client = new Client([
        'headers' => [
            'Content-Type' => 'application/json',
            'Authorization' => config('app.callisto_token'),
        ]
    ]);
    $body = [
            'firstResult'=> 0,
            'data' => '05/05/2022'
        ];
        $response = $client->post('http://'.$this->ip.'/IntegracaoERP'.'/status_pedido',
            ['body' => json_encode($body)]
        );

不要忘记json_encode in body键。