这是我的 Angular服务:
restFactory.getCalcPrice = function (data) {
return $http({
url:"/api/calc",
method:"POST",
data:{"data": data},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
};
FOSRestBundle配置:
fos_rest:
param_fetcher_listener: true
body_listener: true
body_converter:
enabled: true
routing_loader:
default_format: json
view:
view_response_listener: 'force'
mime_types:
json: ['application/json', 'application/json;version=1.0', 'application/json;version=1.1']
format_listener:
rules:
- { path: ^/api, priorities: [ json ], fallback_format: json, prefer_extension: true }
- { path: ^/, priorities: [ 'html', '*/*'], fallback_format: ~, prefer_extension: true }
Symfony 3 控制器:
/**
* @Post("/calc")
* @View()
* @return array
*/
public function getCalcPrice(Request $request)
{
$req = $request->request->all();
$data = $req['data'];
$data = array(
"data" => $data // in Angular recieving null
);
return $data;
}
所以问题是当我发布来自Angular的一些数据时,我无法在Symfony中获取它。 GET请求正常工作。有什么建议? :)
答案 0 :(得分:1)
根据API doc for Request
class属性$request->request
,您可以访问所有$_POST
参数,但是您在有效负载中将数据作为JSON发送:
因此,您应该调用方法getContent()
并手动解码:
$content = $request->getContent();
$json = json_decode($content, true);
$data = $json['data'];