我应该如何使用Axios在Vue中格式化JSON使其看起来像这样?

时间:2020-03-19 21:25:08

标签: javascript json ajax vue.js axios

我花了数小时试图弄清楚如何在Vue.js中格式化JSON以这种方式发送它:

enter image description here

目前,我正在尝试使用FormData()对象进行操作,但结果仍然是:

enter image description here

我的功能如下:

register () {
        var bodyFormData = new FormData();
        bodyFormData.append('firstname', 'Coca');
        bodyFormData.append('lastname', 'Cola')
        console.log(jsonData)
        axios({
          method: 'post',
          url: 'backend/index.php?action=createUser',
          data: bodyFormData,
          headers: {'Content-Type': 'multipart/form-data' }
          })
          .then(function (response) {
              //handle success
              console.log(response);
          })
          .catch(function (response) {
              //handle error
              console.log(response);
          });
      }

我已经通过jQuery AJAX调用在第一张图片上实现了效果,在Vue中使用Axios也可以做到这一点吗?

3 个答案:

答案 0 :(得分:1)

您可以使用JSON.stringify方法并将对象附加到表单数据中。

bodyFormData.append('data', JSON.stringify(jsonData));

答案 1 :(得分:1)

您将显式使用Content-Type: multipart/form-data并发送data参数的表单数据。要发送JSON,请将data设置为要序列化为JSON的对象,然后将application/json用作content-type

async register () {
  try {
    const response = await axios({
      method: 'post',
      url: 'backend/index.php?action=createUser',
      data: { firstname: 'Coca', lastname: 'Cola' },
      headers: {'Content-Type': 'application/json' }
    });
    //handle success
    console.log(response);
  } catch (err) {
    //handle error
    console.log(err);
  }
}

答案 2 :(得分:0)

感谢您的回答,我实际上不得不制作一个FormData并用字符串化的JSON数据填充它。