如何从控制器(Symfony)中的formData获取帖子值



我创建了一个 REST API。从前面,我用公理发送帖子值。(我使用ReactJS)。在Back with Symfony中,在我的控制器中,我想获取帖子值。我该怎么办?我成功了:

从前面:

const data = new FormData();
       let postData = {
            source: 'lcl',
            userLastname: lastname,
            userFirstname: firstname,
            text: message,
        }
data.append('data', postData);
Axios.post('http://127.0.0.1:8000/send', data)
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error)
        });

从我在控制器中,我尝试这样做:

$data = $request->request->get('data');

值返回 [对象对象]...如何获取值(源,用户姓氏等)。

谢谢你的帮助。

你应该解码你的数据:

$data = $request->request->get('data');
if (!empty($data)) {
    $array = json_decode($data, true); // 2nd param to get ass array
    $userLastname =  $array['userLastname']; // etc...
}

现在$array将是一个充满 JSON 数据的数组。删除 json_decode() 调用中的 true 参数值以获取 stdClass 对象。

[object Object]

如果 JS 将对象转换为字符串,则会发生这种情况,您的有效负载永远不会到达您的后端。调用$request->request->get('source')等将起作用。

发生这种情况是因为您将它附加到将隐式转换为字符串的 formdata 对象,请尝试仅传递 postData 而不是您的数据。你会成功的。

就像

Axios.post('http://127.0.0.1:8000/send', postData)

编辑:抱歉,请求转换可能是可选的。从 fosrestbundle 中选择 Param 监听器或使用 https://github.com/symfony-bundles/json-request-bundle

最新更新