![](http://habrastorage.org/getpro/habr/avatars/1f5/07c/5aa/1f507c5aa90cbb57778d0c45e776d8ae.png)
Handling POST requests from AngularJs in Symfony2
- Transfer
- Tutorial
![](https://habrastorage.org/files/2f1/bba/724/2f1bba724a364049904b57a1fea98d54.png)
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
![image](https://habrastorage.org/getpro/habr/post_images/d37/c86/3a8/d37c863a80a1269ab7e09452a86b3a8b.gif)
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: