Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

只谈情不闲聊 提交于 2019-12-24 13:09:08

问题


I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.

This is the angular service handling the requests

myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){

    return $resource(API_URL + '/books/:bookId', {bookId: '@bookId'}, {
        get: { method: 'GET', isArray:true },
        update: { method: 'PUT'},
        save: { method: 'POST'},
        delete: {method:'DELETE'},
    });

}]);

When I submit a book from the Angular app I can catch the POST in Slim by using

$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty

When I use Postman and I perform a POST I can catch the POST in Slim by using

//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();

I don't get why there is this difference. Could you please explain?

Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?


回答1:


The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.




回答2:


You could still use

$post_b = $app->request->post()

in Slim.

As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON. If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:

Object.toparams = function ObjecttoParams(obj) {
    var p = [];
    for (var key in obj) {
        p.push(key + '=' + encodeURIComponent(obj[key]));
    }
    return p.join('&');
};

$http({
    method: 'POST',
    url: url,
    data: Object.toparams(myobject),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

myobject is the data in JSON format that is going to be created




回答3:


Thanks Josh..Your answers works for me.

Steps to follow:

1.You need to send request in json format under raw tab like this:

{"username":"admin","password":"admin"}

2.You need to set Content-Type to application/json in the headers.

That's it and it will work.



来源:https://stackoverflow.com/questions/27859405/slim-postman-and-angularjs-app-request-getbody-vs-app-request-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!