AngularsJS POST JSON data to Symfony2

无人久伴 提交于 2019-12-12 14:08:13

问题


I would like to know why this is not working , I have a AngularJS app witch sends trough AJAX data to a Symfony2 Application. As you can see, data is sent in my network console

<?php

namespace Supbox\CloudBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
class FolderController extends Controller
{
    public function createAction(){
        $post = $this->getRequest()->request;
        $name = $post->get("name");
        $folder = $post->get("folder");
        var_dump($post);
        die; 
    }
}

AngularJS code

    $http({
            method: 'POST', 
            url: route.folder.create, 
            data: {
                folder: $scope.id,
                name: name
            }
        })

Opera Network Console Output

Request URL:http://localhost/supbox/web/box/folder/create
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept-Encoding:gzip,deflate,lzma,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:25
Content-Type:application/json;charset=UTF-8
Host:localhost
Origin:http://localhost
Referer:http://localhost/supbox/web/box/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36 OPR/20.0.1387.82
Request Payloadview source
{folder:1, name:Ang}
Response Headersview source
Connection:Keep-Alive
Content-Length:431
Content-Type:text/html
Date:Mon, 24 Mar 2014 13:25:53 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.4 (Win64) OpenSSL/1.0.1d PHP/5.4.12
X-Powered-By:PHP/5.4.12

回答1:


If you (Angular JS) post data through header as JSON you need to change your code like this:

public function createAction(){
    $post = $this->getRequest()->getContent();
    $post = json_decode($post);
    $name = $post->name;
    $folder = $post->folder;
    var_dump($post);
    var_dump($name); // null
    var_dump($folder); // null
    die; 
}



回答2:


Dont know why, Angular $http sends data as request body, JSON encoded whereas Symfony2 is reading $_GET and $_POST arrays.

So you got 2 solutions:

1- Update Php code, you could override SF2 Request class (https://gist.github.com/ebuildy/fe1e708e466dc13dd736)

2- Update Js code, you can "transform" the $http request (https://gist.github.com/bennadel/11212050)




回答3:


A bundle has been created to solve this problem, and it's very light.

qandidate-labs/symfony-json-request-transformer



来源:https://stackoverflow.com/questions/22610986/angularsjs-post-json-data-to-symfony2

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