使用axios不发送参数的POST请求

Pra*_*esh 2 symfony vue.js axios

我试图使用以下代码将一些数据从Vue.js发布到基于Symfony的后端.

       updateQuestion : function() {
            axios.post('/staff/question/api/' + this.id,{
                    id : 'test',
                    name : 'sree'
            })
                .then( response => {

                console.log(response);
            })
                .catch(error => {
                    console.log(error);
                })
        },
Run Code Online (Sandbox Code Playgroud)

但是,我附加到POST请求的参数未到达我的控制器.所以,我尝试了POST请求的备用格式,但参数还没有到达控制器.请告诉我出了什么问题.

替代格式:

 updateQuestion : function() {
            axios({

                method : 'POST',
                url : '/staff/question/api/' + this.id,
                data: {
                    id : 'test',
                    name : 'sree'
                }

            })
                .then( response => {

                console.log(response);
            })
                .catch(error => {
                    console.log(error);
                })
        },
Run Code Online (Sandbox Code Playgroud)

小智 12

我也遇到过这个问题!我的帖子数据在控制器中找到:

$request->getContent();
Run Code Online (Sandbox Code Playgroud)

我的vue脚本

onSubmit() {
  axios.post('/test/post/data', { test: "test" })
    .then(response => {
      console.log(response.data);
    });
},
Run Code Online (Sandbox Code Playgroud)

我的Symfony控制器:

public function postData(Request $request)
{
    $data = $request->getContent();
    $data = json_decode($data, true);

    return $this->json($data);
}
Run Code Online (Sandbox Code Playgroud)


Blo*_*ops 5

安装 FOSRestBundle 来解决这个问题。

composer require friendsofsymfony/rest-bundle
Run Code Online (Sandbox Code Playgroud)

https://github.com/FriendsOfSymfony/FOSRestBundle

使用此包,传入的 json 请求将自动转换为数组,直接在$request->request->all()或 中可用$request->request->get('myparam')

文档摘录:

这个包提供了各种工具来使用 Symfony 快速开发 RESTful API 和应用程序。功能包括:

  • 一个视图层,用于启用输出和格式不可知的控制器
  • 一个自定义路由加载器,用于生成 url 的以下 REST 约定
  • 接受标头格式协商,包括处理自定义 mime 类型
  • HTTP 请求正文和接受标头的 RESTful 解码
  • 用于发送适当的 HTTP 状态代码的异常控制器