POST axios 请求不发送参数

POST Requests with axios not sending parameters

我正在尝试 POST 使用以下代码将一些数据从 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);
                })
        },

但是,我附加到 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);
                })
        },

你的语法没有问题。但是检查 this.id - 如果你没有做任何错误并且 this.id 是未定义的,或者什么的。如果 this.id 没问题,则在控制器中记录完整的请求并查找数据。

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

我也遇到了这个问题! 我的 post 数据在控制器中找到:

$request->getContent();

我的 vue 脚本

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

我的 Symfony 控制器:

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

    return $this->json($data);
}

安装 FOSRestBundle 来解决这个问题。

composer require friendsofsymfony/rest-bundle

https://github.com/FriendsOfSymfony/FOSRestBundle

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

文档摘录:

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

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

您可以在 JavaScript 文件中执行以下操作,而不是使用 $request->getContent();,以便能够在后端使用 $request->request->all()

我需要这个来编写测试,因为 $request->getContent(); 在我的测试中是空的。

const params = new URLSearchParams();
params.append('id', 123456);
params.append('name', 'some name');

axios({
  method: 'post',
  url: '/staff/question/api/' + this.id,
  data: params
});

另请参阅:https://github.com/axios/axios/issues/1195#issuecomment-347021460

如果你不想使用 $request->getContent(); 但像 user6748331 建议的那样像 $_POST 那样处理它,这里有一个函数:

utils.js(或其他):

export function preparePostData(data) {
    const formData = new FormData();
    for (let key in data) {
        if (data.hasOwnProperty(key)) { // for the sake of editor not screaming
            formData.append(key, data[key]);
        }
    }

    return formData;
}

前端某处:

import {preparePostData} from "utils";
const data = {
  firstname: "Foo",
  lastname: "Bar"
}

const postData = preparePostData(data);
axios.post("/whereever", postData);

在您的 Symfony 控制器中:

$data = $request->request->all();

P.S。这仅适用于普通对象。如果你想要 post 数组和其他东西,你可能还需要在 Symfony 中 json_decode。或者更改 preparePostData 函数使其递归。