doue2666 2014-09-10 20:34
浏览 41
已采纳

从Angular到Laravel的POST不起作用

I have been working on a REST API that is working correctly. Through a client like Postman, I can test and see my changes, deletions, additions, etc. working as long as I encode the data with x-www-form-urlencoded

However now I'm trying to hook it up with Angular. I can make a GET request just fine, the POST is what's hanging me up.

Here's my scratch directive doing the dirty work in Angular .js (I know I need to create a service for this):

app.directive('addGoal', function($http) {
    return {
        restrict: 'E',
        templateUrl: 'js/templates/add-goal.html',
        link: function(scope) {
            scope.submit = function(data) {
                data = {
                    goal: {
                        summary: "asdf",
                        details: "asdf",
                        start_date: "2014-01-01",
                        end_date: "2014-01-02"
                    }
                };
                console.log(data);
                $http({
                    url: 'http://localhost:8000/v1/goal/',
                    method: 'POST',
                    data: data,
                    headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
                }).
                success(function() {
                    console.log(data);
                }).
                error(function() {
                    console.log('error');
                });
            };
        }
    };
});

The call is fired and the .success() function operates normally, however the data isn't POSTed in my API and therefore not saved to the database.

When I get a response back, it acts like the formatting isn't right, as it errors out on validation:

{"error":true,"message":{"summary":["The summary field is required."],"details":["The details field is required."],"start_date":["The start date field is required."],"end_date":["The end date field is required."]}}

Just for reference, here is the store() function of my Controller in Laravel doing the API work:

public function store()
{
    $goal = new Goal;
    $goal->summary = Request::get('summary');
    $goal->details = Request::get('details');
    $goal->user_id = Auth::user()->id;
    $start_date_entered = Request::get('start_date');
    $end_date_entered = Request::get('end_date');
    $goal->start_date = date('Y-m-d', strtotime($start_date_entered));
    $goal->end_date = date('Y-m-d', strtotime($end_date_entered));

    $validation = Validator::make(Request::all(), [
        'summary' => 'required|max:255',
        'details' => 'required|max:255',
        'start_date' => 'required|date',
        'end_date' => 'required|date'
    ]);

    if ($validation->fails())
    {
        $messages = $validation->messages();
        return Response::json(array(
            'error' => true,
            'message' => $messages),
            200
        );
    }
    else
    {
        $goal->save();

        return Response::json(array(
            'error' => false,
            'goal' => $goal->toArray()),
            200
        );
    }
}

I created a test route like this:

Route::post('/test', function()
{
    // First we fetch the Request instance
    $request = Request::instance();

    // Now we can get the content from it
    $content = $request->getContent();

    var_dump($content);
});

And surprisingly my response back looked like this:

string(94) "{"goal":{"summary":"asdf","details":"asdf","start_date":"2014-01-01","end_date":"2014-01-02"}}"

If the success function is firing, it's hitting the API, right? How can I troubleshoot this more to find out the real problem? I'm stuck on where I should go next to get this data into the API so it can store it properly, as it's doing in the REST client.

EDIT

After review, the actual problem involved the way I set up Laravel and it's inability to understand that JSON was being passed in. A simple fix involved changing the Request::get to Input::json()->get():

$goal->summary = Input::json()->get('summary');
  • 写回答

1条回答 默认 最新

  • drutcs7210 2014-09-10 21:00
    关注

    I use Telerik fiddler : http://www.telerik.com/fiddler for such purpose. It gives following information.

    1. Request details, like data, method, request headers, Auth headers, cookies etc.
    2. Response details, data, headers

    It also allows us to replay the given request by modifying the method and data to check how service behaves with different inputs.

    Hope it helps.

    Moreover, I think even if you change the data format like follows, it should work.

                   data = {
                            summary: "asdf",
                            details: "asdf",
                            start_date: "2014-01-01",
                            end_date: "2014-01-02"  
                    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题