Laravel-使用外部请求时POST数据为空 [英] Laravel - POST data is null when using external request

查看:364
本文介绍了Laravel-使用外部请求时POST数据为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to laravel, and I'm trying to implement a simple rest api.

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

I have the controller implemented, and tested via unit testing.

我的问题出在POST请求上.

My problem is with the POST request.

通过测试Input:json包含数据,它通过外部rest客户端返回null.

Via the tests Input:json has data, via an external rest client it returns 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项目,只需使用以下代码:

I've instanciated a new laravel project and just have this code:

路线

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":[]}

谁能指出我出了什么问题.

Can anyone point me to what is wrong.

这确实使我无法使用laravel,我真的很喜欢这个概念.

This is really preventing me to use laravel, and I really liked the concept.

推荐答案

由于您将JSON作为HTTP正文发布,因此您无法通过 Input :: all()来获取它; 您应该使用:

Because you are posting JSON as your HTTP body you don't get it with Input::all(); You should use:

$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');

这篇关于Laravel-使用外部请求时POST数据为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆