wwr
wwr

Reputation: 327

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

Upvotes: 1

Views: 2875

Answers (3)

Kerisnarendra
Kerisnarendra

Reputation: 913

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

Upvotes: 0

Md. Shamsad ahmed
Md. Shamsad ahmed

Reputation: 1

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.

Upvotes: -1

Josh Lockhart
Josh Lockhart

Reputation: 86

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.

Upvotes: 5

Related Questions