wwr wwr - 3 months ago 27
reST (reStructuredText) Question

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

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()?

Answer

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.