axios POST请求击中控制器上的url,但将空值设置为我的POJO类,当我在chrome中通过开发人员工具时,有效载荷包含数据。我做错了什么?

Axios POST请求

var body = {
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
}

axios({
    method: 'post',
    url: '/addUser',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

浏览器响应:

如果我设置头信息为:

headers:{
  Content-Type:'multipart/form-data'
}

请求抛出错误

在发布多部分/表单数据时出错。内容类型报头缺少边界

如果我在邮递员中提出相同的请求,它就会正常工作,并为我的POJO类设置值。

有人能解释如何设置边界或如何使用axios发送表单数据吗?


当前回答

 transformRequest: [
  function(data, headers) {
    headers["Content-Type"] = "application/json";
    return JSON.stringify(data);
  }
]

试试这个,很管用

其他回答

上面的方法对我来说很有效,但因为这是我经常需要的东西,所以我使用了一个基本的方法来制作平面物体。注意,我也在使用Vue而不是REACT

packageData: (data) => {
  const form = new FormData()
  for ( const key in data ) {
    form.append(key, data[key]);
  }
  return form
}

这对我有用,直到我遇到更复杂的数据结构与嵌套对象和文件,然后让以下

packageData: (obj, form, namespace) => {
  for(const property in obj) {
    // if form is passed in through recursion assign otherwise create new
    const formData = form || new FormData()
    let formKey

    if(obj.hasOwnProperty(property)) {
      if(namespace) {
        formKey = namespace + '[' + property + ']';
      } else {
        formKey = property;
      }

      // if the property is an object, but not a File, use recursion.
      if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
        packageData(obj[property], formData, property);
      } else {
        // if it's a string or a File
      formData.append(formKey, obj[property]);
      }
    }
  }
  return formData;
}

https://www.npmjs.com/package/axios

它的工作

// "content-type": "application/x-www-form-urlencoded", //提交

import axios from 'axios';

let requestData = {
      username : "abc@gmail.cm",
      password: "123456"
    };
   
    const url = "Your Url Paste Here";

    let options = {
      method: "POST",
      headers: { 
        'Content-type': 'application/json; charset=UTF-8',

        Authorization: 'Bearer ' + "your token Paste Here",
      },
      data: JSON.stringify(requestData),
      url
    };
    axios(options)
      .then(response => {
        console.log("K_____ res :- ", response);
        console.log("K_____ res status:- ", response.status);
      })
      .catch(error => {
        console.log("K_____ error :- ", error);
      });

获取请求

fetch(url, {
    method: 'POST',
    body: JSON.stringify(requestPayload),           
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
        Authorization: 'Bearer ' + token,
    },
})
    // .then((response) => response.json()) .  // commit out this part if response body is empty
    .then((json) => {
        console.log("response :- ", json);
    }).catch((error)=>{
        console.log("Api call error ", error.message);
        alert(error.message);
});

2020 ES6的做法

我在html中绑定了这样的数据:

数据:

form: {
   name: 'Joan Cap de porc',
   email: 'fake@email.com',
   phone: 2323,
   query: 'cap d\ou'
   file: null,
   legal: false
},

onSubmit:

async submitForm() {
  const formData = new FormData()
  Object.keys(this.form).forEach((key) => {
    formData.append(key, this.form[key])
  })

  try {
    await this.$axios.post('/ajax/contact/contact-us', formData)
    this.$emit('formSent')
  } catch (err) {
    this.errors.push('form_error')
  }
}

在发送请求时设置边界(服务器用来解析有效负载)。在发出请求之前无法获得边界。因此,更好的方法是从你的FormData中使用getBoundary()。

var formData = new FormData();
formData.append('userName', 'Fred');
formData.append('file0', fileZero);
formData.append('file1', fileOne);

axios({
  method: "post",
  url: "myurl",
  data: formData,
  headers: {
      'Content-Type':  `multipart/form-data; ${formData.getBoundary()}`,
})
  .then(function (response) {
    //handle success
    console.log(response);
  })
  .catch(function (response) {
    //handle error
    console.log(response);
  });

我需要一次使用axios上传许多文件,因为FormData API,我挣扎了一段时间:

// const instance = axios.create(config);

let fd = new FormData();
for (const img of images) { // images is an array of File Object
  fd.append('images', img, img.name); // multiple upload
}

const response = await instance({
  method: 'post',
  url: '/upload/',
  data: fd
})

我没有指定content-type: multipart/form-data头!