
Handling POST requests from AngularJs in Symfony2
- Transfer
- Tutorial

Note
Using Symfony2 and AngularJs in conjunction is a good idea, but there is one problem - the solution out of the box has a communication problem. This post will talk about how to automatically decode JSON requests and use the received data using Request Symfony using the symfony-json-request-transformer library (in fact, there is only one class).
Idea
AngularJs $ http service automatically sends header dataContent-Type: application/json
in a POST request, and Symfony in turn expects application/x-www-form-urlencoded
. For example, let's send a simple JSON object from our angular application:
{
"name": "John"
}
Now in the controller we get this data:
public function postAction(Request $request)
{
$data = json_decode($request->getContent(), true);
echo $data['name']; // John
}
Pretty simple, right? But, unfortunately, we cannot use the ParameterBag interface in the Request object in this case.
If it is
name
optional and has a default value, I would like to receive data like this:$name = $request->request->get('name', 'Ivan');
Fortunately, using the replace method, we can replace the data in the ParameterBag with our decoded JSON.
public function postAction(Request $request)
{
$data = json_decode($request->getContent(), true);
$request->request->replace($data);
echo $request->request->get('name', 'Ivan'); // John
}
Great, it works the way we wanted. But, after all, this is only one controller ...
Implementation

kernel.event_listener
, it:- Check for header request
Content-Type: application/json
- If so - decodes it
- Fill object
Request::$request
- Will return an error code
HTTP 400 Bad Request
if something went wrong
You can see the full code on Github .
Registering an event handler is very simple by simply defining a new service: