从 POST 请求获取数据

Getting data from POST request

我正在尝试使用 AJAX 请求和 VueJS-Ressource 更新我的用户实体的一些数据。

这是我的 AJAX 请求:

           this.$http.post('/profile/edit', {
               description: this.description
           }).then(response => {
               console.log(response);
           }, response => {
               console.log(response);
           });

这是我收到此 AJAX 请求的控制器:

/**
 * @Route("/edit", name="profile_edit")
 * @Method({"POST"})
 */
public function profileEditAction(Request $request) {
    if ($request->isXmlHttpRequest()) {
        /* @var User $user */
        $user = $this->getUser();
        $description = $request->request->get( 'description');

        if (isset($description)) {
            $user->setDescription($description);
            $this->getDoctrine()->getManager()->flush($user);
            return new Response('Updated User description with success !');
        }

        return new Response('No description parameter found');
    }
    return $this->redirectToRoute('homepage');
}

我的问题是,每次我尝试使用 $request->request->get('PARAMETER_NAME') 从我的请求中获取参数时,它 return 一个空值。

虽然我在浏览器中显示我的请求,但我清楚地看到我正在发送一些东西:

完整 AJAX 请求:https://i.gyazo.com/825ea438b09e4df8d8287555a1c841a6.png

希望有人能帮我解决这个问题,谢谢!

尝试将数据作为 FromData 发布(以便 Content-Type 作为 multipart/form-data 发送)。

在 VueJS 中,这样做:

var formData = new FormData();
formData.append('description', this.description);

this.$http.post('/profile/edit', formData)
    .then(response => {
        console.log(response);
    }, reason => {
        console.log(reason);
    });

确保在 Dev Tools -> Network 中您看到发送的数据为 Form Data(而不是 Request有效负载 ).

在服务器上执行 var_dump( $request->request->all() ) 并查看 request 包含的内容。