axios post请求发送表单数据 [英] axios post request to send form data

查看:136
本文介绍了axios post请求发送表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

axios POST request is hitting the url on the controller but setting null values to my POJO class, when I go through developer tools in chrome, the payload contains data. What am I doing wrong?

Axios POST Request:

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);
});

Browser Response:

If I set headers as:

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

The request throws the error

Error in posting multipart/form-data. Content-Type header is missing boundary

If I make the same request in postman it's working fine and sets values to my POJO class.

Can anyone explain how to set boundary or how can I send form data using axios.

解决方案

You can post axios data by using FormData() like:

var bodyFormData = new FormData();

And then add the fields to the form you want to send:

bodyFormData.append('userName', 'Fred');

If you are uploading images, you may want to use .append

bodyFormData.append('image', imageFile); 

And then you can use axios post method (You can amend it accordingly)

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

Related GitHub issue:

Can't get a .post with 'Content-Type': 'multipart/form-data' to work @ axios/axios

这篇关于axios post请求发送表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆