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

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

问题描述

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

如果我在邮递员中发出相同的请求,则可以正常工作,并将值设置为我的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.

推荐答案

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

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

bodyFormData.set('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);
    });

您可以阅读更多的此处

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

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