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

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

问题描述

axios POST 请求正在访问控制器上的 url,但为我的 POJO 类设置了空值,当我在 chrome 中浏览开发人员工具时,有效负载包含数据.我做错了什么?

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 请求:

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'
}

请求抛出错误

发布多部分/表单数据时出错.Content-Type 标头缺少边界

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

如果我在 postman 中发出相同的请求,它就可以正常工作并将值设置为我的 POJO 类.

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

谁能解释一下如何设置边界或如何使用 axios 发送表单数据.

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

推荐答案

您可以使用 FormData() 像:

var bodyFormData = new FormData();

然后将字段添加到您要发送的表单中:

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

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

如果您要上传图片,您可能需要使用 .append

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

bodyFormData.append('image', imageFile); 

然后你可以使用axios post方法(你可以相应地修改它)

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

相关的 GitHub 问题:

Related GitHub issue:

无法获得带有Content-Type"的 .post:multipart/form-data"' 工作@axios/axios

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

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