问题描述
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: '[email protected]'
}
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类.
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.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发布请求以发送表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!